Linq GroupJoin , Join
static void Main(string[] args) { List<Person> persons = new List<Person> { new Person {Id = 1 }, new Person {Id = 2 }, }; List<Student> students = new List<Student> { new Student {Id = 1, Name = "a", }, new Student {Id = 1, Name = "b", }, new Student {Id = 2, Name = "c", }, new Student {Id = 2, Name = "d", }, }; { //Lambda 写法 var temp = persons.GroupJoin(students, p => p.Id, s => s.Id, (p, s) => new Person { Id = p.Id, Students = s.ToList() }).ToList(); } { //Linq 写法 var temp = (from p in persons join s in students on p.Id equals s.Id into ss select new Person { Id = p.Id, Students = ss.ToList() }).ToList(); } Console.ReadKey(); } public class Person { public int Id { get; set; } public List<Student> Students { get; set; } } public class Student { public int Id { get; set; } public string Name { get; set; } }
GroupJoin 相当于数据库的 Left Join
Join 相当于数据库的 Inner Join