[c#] Getting a count of rows in a datatable that meet certain criteria

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?

This question is related to c# datatable count criteria

The answer is


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.


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

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

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;

Try this

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

int row_count = dt.Rows.Count;

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.


int numberOfRecords = 0;

numberOfRecords = dtFoo.Select().Length;

MessageBox.Show(numberOfRecords.ToString());

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to datatable

Can't bind to 'dataSource' since it isn't a known property of 'table' How to get a specific column value from a DataTable in c# Change Row background color based on cell value DataTable How to bind DataTable to Datagrid Find row in datatable with specific id Datatable to html Table How to Edit a row in the datatable How do I use SELECT GROUP BY in DataTable.Select(Expression)? How to fill a datatable with List<T> SqlBulkCopy - The given value of type String from the data source cannot be converted to type money of the specified target column

Examples related to count

Count the Number of Tables in a SQL Server Database SQL count rows in a table How to count the occurrence of certain item in an ndarray? Laravel Eloquent - distinct() and count() not working properly together How to count items in JSON data Powershell: count members of a AD group How to count how many values per level in a given factor? Count number of rows by group using dplyr C++ - how to find the length of an integer JPA COUNT with composite primary key query not working

Examples related to criteria

Hibernate Criteria Join with 3 Tables Hibernate Criteria Restrictions AND / OR combination How to properly express JPQL "join fetch" with "where" clause as JPA 2 CriteriaQuery? Hibernate Criteria for Dates Getting a count of rows in a datatable that meet certain criteria How to get SQL from Hibernate Criteria API (*not* for logging) How to get distinct results in hibernate with joins and row-based limiting (paging)? JPA and Hibernate - Criteria vs. JPQL or HQL Hibernate Query By Example and Projections