Click here to Skip to main content
15,906,558 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
My datatable like

Company	Name	Department
A	Raja	Mechanical
B	Mano	Electrical
A	Mohan	Computer
B	Rajesh	Computer
C	Siva	Robotics
D	Jeeva	Computer
C	Prakash	Electrical
A	Vinoth	Mechanical


I want to group like below

Company	Name	Department
A	Raja	Mechanical
A	Mohan	Computer
A	Vinoth	Mechanical
B	Mano	Electrical
B	Rajesh	Computer
C	Siva	Robotics
C	Prakash	Electrical
D	Jeeva	Computer



Company Name have to group like this. How can i Group that data in datatable using LINQ .. Note : I want to grouping not sorting. Please help me.

What I have tried:

I have tried the below, but its return first row of the grouping data not all. i want all grouped data in datatable

dt.AsEnumerable().GroupBy(row => row.Field<string>("Company")).Select(g => g.First()).CopyToDataTable()
Posted
Updated 12-Jul-17 23:13pm
v2
Comments
Karthik_Mahalingam 13-Jul-17 5:02am    
are you gonna display it in somewhere?
SnvMohan 13-Jul-17 5:06am    
s, i have to group that data's and displayed in somewhere else, but i can received datatable like the above
Karthik_Mahalingam 13-Jul-17 5:07am    
how many fields does the table has?
SnvMohan 13-Jul-17 5:08am    
10 columns
Karthik_Mahalingam 13-Jul-17 5:15am    
create a entity class and convert the datatable to list and use linq to group by then display it, Linq to entities will make your job easier.

1 solution

You don't normally reorder (sort) a DataTable - and that's what your example shows, Grouping is a different and more complex operation - instead to reorder the view of that data as part of your presentation layer, or order the data before it arrives at the DataTable but using ORDER BY as part of your original SQL query. Assuming this is WinForms, look at the DataGridView.Sort Method (DataGridViewColumn, ListSortDirection) (System.Windows.Forms)[^] or investigate the DataView Class (System.Data)[^] which gives you a logt better control over the presentation.
 
Share this answer
 

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