【问题标题】:Use LINQ to concatenate multiple rows list with same value into single row使用 LINQ 将具有相同值的多行列表连接成单行
【发布时间】:2019-01-30 07:17:26
【问题描述】:

使用 Linq 查询对对象列表中的重复值进行分组。

我将以下数据作为名为“SudentAssessment”的表格,其中包含这些数据。

AssessmentId    Username        SITSupervisor    WorkSupervisor
1              iwsp.student001  iwsp.staff001   iwsp.supervisor001
2              iwsp.student001  iwsp.staff002   iwsp.supervisor001
3              iwsp.student002  iwsp.staff001   iwsp.supervisor002
4              iwsp.student003  iwsp.staff003   iwsp.supervisor003
5              iwsp.student004  iwsp.staff001   iwsp.supervisor004
6              iwsp.student004  iwsp.staff005   iwsp.supervisor004
7              iwsp.student005  iwsp.staff003   iwsp.supervisor005

这里的问题是行号 1,2 和 5,6 具有相同的数据,但唯一的区别是 SIT 主管的详细信息不同。这些每一行都填充到 StudentAssessmentDTO 中,如下所示。

public class StudentAllocationDTO
{
     public int AssessmentId {get;set;}
     public string Username {get;set;}
     public string SITSupervisor {get;set;}
     public string WorkSupervisor {get;set;}
}

根据当前的实现,我在调用返回包含所有 7 条记录的 List 的方法时。由于第 1,2 行和第 5,6 行在“SITSupervisor”中有更多唯一区别,我想在 c# 中使用 LINQ 分配给下面的 DTO 结构。

public class NEWStudentAllocationDTO
{
     public int AssessmentId {get;set;}
     public string Username {get;set;}
     public List<string> SITSupervisor {get;set;}
     public string WorkSupervisor {get;set;}
}

如果您需要进一步澄清,请在评论中告诉我。

【问题讨论】:

  • 我不明白你的问题,你期望的结果是什么?你想把它们分组吗?
  • 如果您选择第 1 行和第 2 行。应该采用哪个 AssessmentId?如果同一个学生的 WorkSupervisor 不同,该怎么办?
  • 您可以使用.GroupBy(c =&gt; new {AssessmentId = c.AssessmentId, Username = c.Username})。分组后,您可以遍历项目并实例化您的 NEWStudentAllocationDTO
  • @Oliver AssessmentId 在这里不会成为问题。我想填充结果以在 Jquery 表中展示。
  • AssessmentId 是一个问题,因为它是您的 NewStudentAllocationDTO 类的属性。

标签: c# .net list linq linq-to-objects


【解决方案1】:

按包含公共属性的匿名类型对它们进行分组。

        IEnumerable< NEWStudentAllocationDTO> grouped = l.GroupBy(x => new { x.Username, x.WorkSupervisor })
            .Select(x => new NEWStudentAllocationDTO()
            {
                AssessmentId = x.Key.AssessmentId,
                WorkSupervisor = x.Key.WorkSupervisor,
                Username = x.Key.Username,
                SITSupervisor = x.Select(y => y.SITSupervisor).ToList()
            });

【讨论】:

  • 您应该从匿名类型中删除 AssessmentId。否则不会对任何内容进行分组(根据给定的示例数据)。
  • 这是真的。我留下了它,因为我想知道 NEWStudentAllocationDTO 类型也包含这样的字段,而不是列表。 EDIT2:我删除它。
  • 这也是我最大的问题。
  • @Malior 刚刚理解了阅读您的答案的要求,x.Select(y =&gt; y.SITSupervisor).ToList() 可能会返回我理解的 SITSupervisors 列表?有趣的是我不知道这是可能的:)
  • 感谢@Malior 的回答。它对我很有效。
猜你喜欢
  • 1970-01-01
  • 2017-09-25
  • 2021-11-24
  • 2010-10-11
  • 1970-01-01
  • 2011-09-18
  • 2017-01-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多