【问题标题】:GroupBy with linq to DataTableGroupBy 与 linq 到 DataTable
【发布时间】:2018-04-12 06:39:53
【问题描述】:

我有下面的数据表:

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 指令中获得目标(每个实体一行)。谢谢。

【问题讨论】:

  • 您只需要 linq 的解决方案吗?我正在考虑在 linq 之外发布解决方案
  • 你试过什么?你哪里有问题?你不知道如何在数据表上使用 LINQ?你不知道如何在 linq 中进行分组吗?您不知道如何聚合您的数据以创建备注字段吗?还有什么?
  • 它不是重复的 - lambda 函数 c# 语法与 vb 不同,尤其是对于初学者。

标签: vb.net linq


【解决方案1】:

从您的答案开始并向后工作,您希望按EntityId 分组并将不同的Remarks 连接在一起。使用您现有的 lambda 查询作为基础,只需简化它(尽管我通常会在 LINQ 中执行“Remark IS NOT NULL”):

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

【讨论】:

  • 谢谢。我没有linq就做到了。但是下周我会试试你的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-22
  • 1970-01-01
  • 2011-11-09
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多