Click here to Skip to main content
15,894,017 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have a DataTable and I want to apply a group by to it. How would I do that?

Example: If first id(100) has 3 records and and another ID(1001) has 2 records; in the DataTable all records come through in different rows. How do I do group by on the DataTable?
Posted
Updated 24-Jan-14 0:29am
v3

1 solution

You cannot do a group by inside a DataTable. You need to do the group by in the query that gets you the data. If you can't do this, you need to convert your data out, perform the group by and then allocate it back to a DataTable. Here's an example of how to do this:
C#
public DataTable GroupByName(DataTable table)
{
  return table.AsEnumerable().GroupBy(gb => gb.Field<string>("Name")).Select(sel => sel.First()).CopyToDataTable();
}
 
Share this answer
 
Comments
skydger 24-Jan-14 6:08am    
+5!
kamalsekhar 24-Jan-14 7:00am    
Hi Pete,
Its taking only one row data from datatable. i need to take(grup by) multiple row from datatable.

EX-
ID col1 col2
100 50 70
100 40 50
100 20 60

These data is comming in datatable.I want to display multiple row in a single row when it is same ID. how to do group for datatable column
Pete O'Hanlon 27-Jan-14 4:38am    
You're talking about pivoting your data here, not grouping data. Doing this inside your DataTable would not be practical as you can end up with varying numbers of columns. If I were you, and I were doing this using an RDBMS, I would look to see if I could get the data back pivoted.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900