获取符合特定条件的数据表中的行数 [英] Getting a count of rows in a datatable that meet certain criteria

查看:181
本文介绍了获取符合特定条件的数据表中的行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个datatable,dtFoo,并希望获得符合特定标准的行数。



编辑:此数据不存储在数据库,所以使用SQL不是一个选项。



在过去,我已经使用以下两种方法来实现这一点:



方法1

  int numberOfRecords = 0; 
DataRow [] rows;

rows = dtFoo.Select(IsActive ='Y');
numberOfRecords = rows.Length;

Console.WriteLine(Count:+ numberOfRecords.ToString());

方法2

  int numberOfRecords = 0; 

foreach(dtFoo.Rows中的DataRow行)
{
if(row [IsActive]。ToString()==Y)
{
numberOfRecords ++;
}
}

Console.WriteLine(Count:+ numberOfRecords.ToString());

我的商店正在努力规范一些事情,这是一个已经出现的问题。我想知道哪些方法在性能方面是最好的(以及为什么),以及最常用的方法。



还有更好的方法实现所需的结果?

解决方案

一个简单的方法是将原始帖子中发布的内容与单个语句相结合:

  int numberOfRecords = dtFoo.Select(IsActive ='Y') 

另一种完成此操作的方法是使用Linq方法:


$ b $ (x => x [IsActive] ToString()==Y)。ToList()。计数;

注意这需要包括 System.Linq


I have a datatable, dtFoo, and would like to get a count of the rows that meet a certain criteria.

EDIT: This data is not stored in a database, so using SQL is not an option.

In the past, I've used the following two methods to accomplish this:

Method 1

int numberOfRecords = 0;
DataRow[] rows;

rows = dtFoo.Select("IsActive = 'Y'");
numberOfRecords = rows.Length;

Console.WriteLine("Count: " + numberOfRecords.ToString());

Method 2

int numberOfRecords = 0;

foreach (DataRow row in dtFoo.Rows)
{
    if (row["IsActive"].ToString() == "Y")
    {
        numberOfRecords++;
    }
}

Console.WriteLine("Count: " + numberOfRecords.ToString());

My shop is trying to standardize on a few things and this is one issue that has come up. I'm wondering which of these methods is best in terms of performance (and why!), as well as which is most commonly used.

Also, are there better ways to achieve the desired results?

解决方案

One easy way to accomplish this is combining what was posted in the original post into a single statement:

int numberOfRecords = dtFoo.Select("IsActive = 'Y'").Length;

Another way to accomplish this is using Linq methods:

int numberOfRecords = dtFoo.AsEnumerable().Where(x => x["IsActive"].ToString() == "Y").ToList().Count;

Note this requires including System.Linq.

这篇关于获取符合特定条件的数据表中的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆