LinQ DataTable分组依据 [英] LinQ DataTable Group By

查看:59
本文介绍了LinQ DataTable分组依据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在vb.net应用程序中有一个数据表.数据表如下所示:

I have a datatable in vb.net application. the data table is looking like this:

State Level City
AL     T     Arlton
AL     T     Brton
AL     T     Rurton
CO     T     Dver
CO     T     Crodo
WA     T     Blain
WA     T     Bwelham

我想对状态进行分组并进行循环 我尝试了以下操作,但未按预期工作. 请帮助

I would like to group the state and do a loop I tried the following but is not working as expected. please help

到目前为止我尝试过的:

what I tried so far:

Dim result = From r In dt Group r By state = r(0) Into Group Select Group
For Each r In result
    Console.WriteLine(r("State"))
Next

循环的输出应为

AL
CO
WA

谢谢

推荐答案

您不能在数据表上调用GroupBy.因此,您可以先使用AsEnumerable()方法将数据表转换为集合,然后再应用分组依据

You cannot call GroupBy on a datatable. So you may first convert the datatable to a collection using the AsEnumerable() method and then apply your group by

Dim itms = dt.AsEnumerable().[Select](Function(x) New With {
    Key .City = x.Field(Of String)("City"),
    Key .State = x.Field(Of String)("State"),
    Key .Level = x.Field(Of String)("Level")
})



Dim uniqueStatesgroupedStates = itms.GroupBy(Function(s) s.State, Function(p) p,
                                                                Function(k, v) New With {
    Key .State = k,
    Key .Item = v
})

' IF you want group records based in State

For Each r In uniqueStatesgroupedStates
    Console.WriteLine(r.State)
Next

' IF you want only Unique states from your data table
Dim uniqueStates = itms.[Select](Function(s) s.State).Distinct().ToList()

For Each r In uniqueStates
        Console.WriteLine(r)
Next

您的预期输出看起来只需要唯一的州名称,在这种情况下,您只需要执行状态选择"属性并在该属性上调用Distinct().

这篇关于LinQ DataTable分组依据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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