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

前端 未结 8 975
不知归路
不知归路 2021-02-01 14:02

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 op

相关标签:
8条回答
  • 2021-02-01 14:06
    int numberOfRecords = 0;
    
    numberOfRecords = dtFoo.Select().Length;
    
    MessageBox.Show(numberOfRecords.ToString());
    
    0 讨论(0)
  • 2021-02-01 14:11
    int numberOfRecords = DTb.Rows.Count;
    int numberOfColumns = DTb.Columns.Count;
    
    0 讨论(0)
  • 2021-02-01 14:11
    int row_count = dt.Rows.Count;
    
    0 讨论(0)
  • 2021-02-01 14:15

    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.

    0 讨论(0)
  • 2021-02-01 14:19

    Try this

    int numberOfRecords = dtFoo.Select("IsActive = 'Y'").Count<DataRow>();    
    Console.WriteLine("Count: " + numberOfRecords.ToString());
    
    0 讨论(0)
  • 2021-02-01 14:25

    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.

    0 讨论(0)
提交回复
热议问题