我有以下数据表:
DefectTypeId EntityId DefectId Remark
------------------------------------------------
1 29000 100 Defect
2 29000 100 Defect
3 29000 200 Ok
1 30000 100 Defect
2 30000 150
9 31000 100 Defect
10 31000 100 Defect
12 31000 200 Ok
如何使用linq获取此表或列表?
EntityId Remark
------------------------
29000 Defect, Ok
30000 Defect
31000 Defect, Ok
提前致谢
修改
我试过了,但它没有用(行没有分组):
Dim query = dt.Select("Remark IS NOT NULL").AsEnumerable().GroupBy(
Function(r) New With {
.EntityId = r.Field(Of Integer)("EntityId"),
.DefectId = r.Field(Of Integer)("DefectId"),
.Remark = r.Field(Of String)("Remark")
}).[Select](
Function(g) New With {
g.Key.EntityId,
.Remark = String.Join(",", g.Select(Function(i) i("Remark")))
})
然后我尝试了这个:
Dim query = (From row In dt.Select("Remark IS NOT NULL")
Group By EntityId = row.Field(Of Integer)("EntityId"),
DefectId = row.Field(Of Integer)("DefectId"),
Remark = row.Field(Of String)("Remark") Into g = Group) _
.Select(Function(i) New With {
i.EntityId,
.Remark = String.Join(",", i.Remark)
})
它更好,但它还不是预期的结果。结果如下:
EntityId Remark
------------------------
29000 Defect
29000 Ok
30000 Defect
31000 Defect
31000 Ok
我可以使用foreach获得我想要的东西,但想知道是否有可能在单个Linq指令中获得目标(每个实体一行)。谢谢。
答案 0 :(得分:0)
从您的答案开始并向后工作,您希望按EntityId
分组并加入不同的Remark
。使用现有的lambda查询作为基础,只需简化它(虽然我会做"备注IS NOT NULL"通常在LINQ中):
Dim Ans = dt.Select("Remark IS NOT NULL") _
.GroupBy(Function(r) r.Field(Of Integer)("EntityId"), Function(r) r.Field(Of String)("Remark")) _
.Select(Function(rg) New With {
.EntityId = rg.Key,
.Remark = String.Join(", ", rg.Distinct())
})
使用VB Query Comprehension的一些优点,你也可以这样做:
Dim Ans2 = From r In dt.Select("Remark IS NOT NULL")
Group r.Field(Of String)("Remark") By Key = r.Field(Of Integer)("EntityId") Into Group
Select New With {.EntityId = Key, .Remark = String.Join(", ", Group.Distinct())}