使用 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/