C# - 使用linq进行数据表分组 [英] C# - datatable grouping using linq

查看:338
本文介绍了C# - 使用linq进行数据表分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据表如



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







公司名称必须像这样分组。我如何使用LINQ将数据分组到数据表中。注意:我想分组而不是排序。请帮帮我。



我的尝试:



我有尝试了以下,但它返回的第一行分组数据并非全部。我希望数据表中的所有分组数据



dt.AsEnumerable()。GroupBy(row => row.Field< string>(Company))。选择( g => g.First())。CopyToDataTable()




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()

推荐答案

您通常不会重新排序(排序)DataTable - 这就是您的示例所显示的内容, 分组是一个不同且更复杂的操作 - 而是将该数据的视图重新排序为表示层的一部分,或者在数据到达DataTable之前对数据进行排序,但使用ORDER BY作为原始SQL查询的一部分。假设这是WinForms,请查看 DataGridView.Sort方法(DataGridViewColumn,ListSortDirection) (System.Windows.Forms) [ ^ ]或调查 DataView类(System.Data) [ ^ ],它可以让您更好地控制演示文稿。
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.


这篇关于C# - 使用linq进行数据表分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆