Getting a count of rows in a datatable that meet certain criteria

北城余情 提交于 2019-12-03 05:28:24

问题


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?


回答1:


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.




回答2:


int numberOfRecords = DTb.Rows.Count;
int numberOfColumns = DTb.Columns.Count;



回答3:


Not sure if this is faster, but at least it's shorter :)

int rows = new DataView(dtFoo, "IsActive = 'Y'", "IsActive",
    DataViewRowState.CurrentRows).Table.Rows.Count;



回答4:


int numberOfRecords = 0;

numberOfRecords = dtFoo.Select().Length;

MessageBox.Show(numberOfRecords.ToString());



回答5:


Try this

int numberOfRecords = dtFoo.Select("IsActive = 'Y'").Count<DataRow>();    
Console.WriteLine("Count: " + numberOfRecords.ToString());



回答6:


If the data is stored in a database it will be faster to send the query to the database instead of getting all data and query it in memory.

A third way to do it will be linq to datasets, but i doubt any of these 3 methods differ much in performance.




回答7:


object count =dtFoo.Compute("count(IsActive)", "IsActive='Y'");



回答8:


int row_count = dt.Rows.Count;


来源:https://stackoverflow.com/questions/5252934/getting-a-count-of-rows-in-a-datatable-that-meet-certain-criteria

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!