【发布时间】: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 => new {AssessmentId = c.AssessmentId, Username = c.Username})。分组后,您可以遍历项目并实例化您的 NEWStudentAllocationDTO -
@Oliver AssessmentId 在这里不会成为问题。我想填充结果以在 Jquery 表中展示。
-
AssessmentId是一个问题,因为它是您的NewStudentAllocationDTO类的属性。
标签: c# .net list linq linq-to-objects