Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 550
Sesame Avatar asked Mar 09 '11 22:03

Sesame


People also ask

How do you count rows in a data table?

data(). rows(). count() gives you the count of rows.

How can count number of rows in Datatable in asp net?

int numberOfRecords = 0; foreach (DataRow row in dtFoo. Rows) { if (row["IsActive"]. ToString() == "Y") { numberOfRecords++; } } Console. WriteLine("Count: " + numberOfRecords.

What is row in Datatable?

Description. Working with rows is a fundamental part of DataTables, and you want to be able to easily select the rows that you want from the table. This method is the row counterpart to the columns() and cells() methods for working with columns and cells in the table, respectively.


1 Answers

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.

like image 68
saluce Avatar answered Oct 01 '22 21:10

saluce