有时候我们从数据库中查询出来数据之后,需要按照DataTable的某列进行分组,可以使用下面的方法实现,代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataTableGroupDemo { class Program { static void Main( string [] args) { // 准备数据 DataTable dt = new DataTable(); // 创建列 DataColumn dcName = new DataColumn( "Name" , typeof ( string )); DataColumn dcAge = new DataColumn( "Age" , typeof (Int32)); DataColumn dcScore = new DataColumn( "Score" , typeof (Int32)); // 添加列 dt.Columns.Add(dcName); dt.Columns.Add(dcAge); dt.Columns.Add(dcScore); // 添加数据 dt.Rows.Add( new object [] { "Tom" , 23, 67 }); dt.Rows.Add( new object [] { "Tom" , 23, 67 }); dt.Rows.Add( new object [] { "Jack" , 21, 100 }); dt.Rows.Add( new object [] { "Greey" , 24, 56 }); dt.Rows.Add( new object [] { "Kevin" , 24, 77 }); dt.Rows.Add( new object [] { "Tom" , 23, 82 }); dt.Rows.Add( new object [] { "Greey" , 24, 80 }); dt.Rows.Add( new object [] { "Jack" , 21, 90 }); #region 使用Linq expression to DataTable group by var query = from p in dt.AsEnumerable() group p by new { name = p.Field< string >( "Name" ),score=p.Field<Int32>( "Score" ) } into m select new { Name = m.Key.name, Score=m.Key.score }; #endregion // 输出 Console.WriteLine( "Linq" ); foreach (var item in query) { Console.WriteLine(item); } Console.WriteLine( "GroupBy" ); IEnumerable<IGrouping< string , DataRow>> result = dt.Rows.Cast<DataRow>().GroupBy<DataRow, string >(dr => dr[ "Name" ].ToString()); foreach (IGrouping< string , DataRow> ig in result) { Console.WriteLine( "key=" + ig.Key + ":" ); foreach (DataRow dr in ig) { Console.WriteLine(dr[ "Name" ].ToString().PadRight(10) + dr[ "Age" ].ToString().PadRight(10) + dr[ "Score" ].ToString().PadRight(10)); } } Console.ReadKey(); } } } |
程序运行效果
到此这篇关于C#对DataTable某列进行分组的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://www.cnblogs.com/dotnet261010/p/11495884.html