-1

How can we get the counts of rows by the value of a given column?

  • I am creating IEnumerable from datatable returned from stored procedure

        DataSet ds = new DataSet();
        // code to get table using sp    
        IEnumerable<DataRow> Myrows = ds.Tables[0].AsEnumerable();
    
  • My table returns data like

       Id | Column1 | Column2 | Column3 |
        1 | xCol1   | xCol2   | xCol3   |
        2 | xCol1   | xyy     | ser     |
        3 | xCol2   | 2324    | ser     |
    
  • now i want to get count of rows with group by Column1 . So my result should be

        Count | Column |
          2   | xCol1  |
          1   | xCol2  |
    
Val Akkapeddi
  • 1,173
  • 10
  • 17
Pragnesh Patel
  • 1,444
  • 3
  • 23
  • 38
  • possible duplicate of [Howto: Count the items from a IEnumerable without iterating?](http://stackoverflow.com/questions/168901/howto-count-the-items-from-a-ienumerablet-without-iterating) – ChrisF Mar 06 '12 at 15:32
  • 1
    I think you are asking the same thing as this question... http://stackoverflow.com/questions/1225710/linq-to-dataset-multiple-group-by-on-a-data-table – Christoph Mar 06 '12 at 15:35
  • Thanks Chrisopher. you are right. i was looking for same thing you suggested – Pragnesh Patel Mar 06 '12 at 15:43
  • var groupQuery = from table in MyTable.AsEnumerable() group table by new { column1 = table["Column1"], column2 = table["Column2"] } into groupedTable select new { x = groupedTable.Key, // Each Key contains column1 and column2 y = groupedTable.Count() } – Pragnesh Patel Mar 06 '12 at 15:43

2 Answers2

0

There are a few ways to do this:

  1. Iterate over the IEnumerable collection and count the elements.
  2. If you don't want to iterate, use Myrows.ToList().Count which will create a list from the IEnumerable collection and get the Count property of the List.

You can use linq to do the group by and get the count from there. Here is an example:

var groups =
  from row in rows
  group rows by row.Column;

foreach (var group in groups)
  Console.WriteLine("key: {0} count: {1}",
    group.Key, group.Count());

Also see this question for more information: Howto: Count the items from a IEnumerable without iterating?

Community
  • 1
  • 1
Michael Hornfeck
  • 1,242
  • 1
  • 16
  • 33
0
    DataSet ds = new DataSet();
    // code to get table using sp    
    var grouped = ds.Tables[0].AsEnumerable().GroupBy(q=>q.Table.Columns["column1"]).Select(q=> new{Count = q.Count(), Column = q});

I've not tried it. But something like that.

auo
  • 572
  • 1
  • 7
  • 16