我们有这样一个DataTable
:
Dim datas = New DataTable() datas.Columns.Add("name") datas.Columns.Add("code") datas.Columns.Add("price") datas.Rows.Add("java", 1, 1.33) datas.Rows.Add("java", 2, 4.66) datas.Rows.Add("java", 3, 7.33) datas.Rows.Add("java", 4, 8.66) datas.Rows.Add("c#", 5, 1.33) datas.Rows.Add("c#", 6, 4.66) datas.Rows.Add("c#", 7, 7.33) datas.Rows.Add("c#", 8, 8.66)
我们希望生成一个按name
列分组,再对分组的进行按code
分组
LINQ代码如下:
Dim x = From r In datas Let s = Convert.ToString(r("name")) Group r By s Into g1 = Group From g2 In (From r2 In g1 Let code = Convert.ToString(r2("code")) Group r2 By code Into Group) Group g2 By s Into Group
某些平台可能不允许匿名类型,那么我们可以使用GroupBy扩展方法来实现相同的功能:
Dim nameGroup = datas.Rows.Cast(Of DataRow).GroupBy(Function(r) Convert.ToString(r("name")))
如果code
没有重复,我们生成Dictionary(of String, Dictionary(of String, DataRow))
:
Dim x3 = nameGroup.ToDictionary(Function(p) p.Key, Function(p) p.ToList().ToDictionary(Function(p1) Convert.ToString(p1("code"))))
假如code
可能重复,我们生成Dictionary(of String, Dictionary(of String, List(of DataRow)))
:
Dim x4 = nameGroup.ToDictionary(Function(p) p.Key, Function(p) p.ToList().GroupBy(Function(x) Convert.ToString(x("code"))).ToDictionary(Function(p1) p1.Key, Function(p2) p2.ToList()))