gpt4 book ai didi

c# - List 到层次结构
转载 作者:太空宇宙 更新时间:2023-11-03 21:07:42 24 4
gpt4 key购买 nike

我有一个 List<Data>数据在哪里

public class Data
{
public string SchoolId {get; set;}
public string SchoolName {get; set;}
public string TeacherId {get; set;}
public string TeacherName {get; set;}
}

列表是扁平的:

SchoolId    SchoolName     TeacherId      TeacherName
1 X 1 Mr X
1 X 2 Mrs Y
2 Y 3 Mr Z
2 Y 1 Mr X

所以基本上一个老师可以属于很多学校。

如何将上面的平面列表转换为 List<School>

public class School
{
public School()
{
this.Teachers = new List<Teacher>();
}
public string SchoolId { get; set; }
public string SchoolName { get; set; }
public List<Teacher> Teachers {get; set;}
}


public class Teacher
{
public string TeacherId { get; set; }
public string TeacherName { get; set; }
}

最佳答案

如果那是 Linq to objects,则使用此代码

var result = list.GroupBy(x=>new {x.SchoolId, x.SchoolName})
.Select(x=>
{
var s = new School();
s.SchoolId = x.Key.SchoolId;
s.SchoolName = x.Key.SchoolName;
s.Teachers.AddRange(x.Select(
y => new Teacher
{
TeacherId = y.TeacherId,
TeacherName = y.TeacherName
}
));

return s;
});

请注意,即使在具有相同 IdTeacher 中,上述代码也会导致重复的 Teacher 实例。

关于c# - List<Object> 到层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40125209/

24 4 0