我有两个不同的集合,如下面的
public class Student
{
public int StudentID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Skills
{
public int SkillID { get; set; }
public int StudentID { get; set; }
public string Keyskill_Name { get; set; }
public int LastUsedYear { get; set; }
}
这里有一个学生可以包含多个keykils
我只想填写下面的新集合
public class StudentDetails
{
public int StudentID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public list<string> Keyskill_Name { get; set; }
}
请帮帮我。提前谢谢。
答案 0 :(得分:1)
GroupJoin
LINQ方法是这种情况的完美解决方案:
List<Student> students = new List<Student>();
List<Skills> skills = new List<Skills>();
List<StudentDetails> studentDetails = students.GroupJoin(skills, student => student.StudentID, skill => skill.StudentID, (student, skillsForStudent) => new StudentDetails
{
FirstName = student.FirstName,
LastName = student.LastName,
StudentID = student.StudentID,
Keyskill_Name = (from skill in skillsForStudent
select skill.Keyskill_Name).ToList()
}).ToList();
GroupJoin
方法?Student
,此处有一个且只有一个对应StudentDetails
。students
)及其在第二组中使用碰撞找到的相应元素。