c# - 使用 LINQ 将具有相同值的多行列表连接成单行

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

使用 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 条记录的列表的方法。由于第 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;}
}

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

最佳答案

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

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

关于c# - 使用 LINQ 将具有相同值的多行列表连接成单行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54435153/

相关文章:

c# - EPPlus 超链接到另一个工作表中的单元格

使用 RefreshReport() 和 ServerReport.SetParameters() 的 c# WinForms ReportViewer 性能问题

c# - 系统.全局化.CultureNotFoundException : Culture is not supported

java - println如何打印一个对象

r - 如何获得两个 R 命名列表之间的差异?

c# - 如何保存与现有实体有父关系的新实体?

c# - 将 ControlTemplate 应用于 WPF TreeViewItem 会降低位图图标质量

c# - 是否有文件字节的 .NET 包装器?

.net - 当我从未将实体添加到上下文时, Entity Framework 错误地保存了实体

C# 类组织和列表