C# linq左连接与分组
1.左连接使用DefaultIfEmpty();
2.分组时候判断newper.FirstOrDefault() == null ? null: newper.ToList()这个经常出错误,如果不判断,会出现空引用的错误
class Program { class Person { public string FirstName { get; set; } public string LastName { get; set; } } class Pet { public string Name { get; set; } public Person Owner { get; set; } } static void Main(string[] args) { Person magnus = new Person { FirstName = "Magnus", LastName = "Hedlund" }; Person terry = new Person { FirstName = "Terry", LastName = "Adams" }; Person charlotte = new Person { FirstName = "Charlotte", LastName = "Weiss" }; Person arlene = new Person { FirstName = "Arlene", LastName = "Huff" }; Pet barley = new Pet { Name = "Barley", Owner = terry }; Pet boots = new Pet { Name = "Boots", Owner = terry }; Pet whiskers = new Pet { Name = "Whiskers", Owner = charlotte }; Pet bluemoon = new Pet { Name = "Blue Moon", Owner = terry }; Pet daisy = new Pet { Name = "Daisy", Owner = magnus }; // Create two lists. List<Person> people = new List<Person> { magnus, terry, charlotte, arlene }; List<Pet> pets = new List<Pet> { barley, boots, whiskers, bluemoon, daisy }; var query = from person in people join pet in pets on person equals pet.Owner into gj from subpet in gj.DefaultIfEmpty() group subpet by person.FirstName into newper select new { newper.Key, Persons = newper.FirstOrDefault() == null ? null: newper.ToList() }; foreach (var ownerAndPet in query) { if (ownerAndPet.Persons != null) { foreach (var p in ownerAndPet.Persons) { Console.WriteLine(string.Format("{0} is owned by {1}", ownerAndPet.Key, p.Name)); } } else { Console.WriteLine(string.Format("{0} is owned by {1}", ownerAndPet.Key, "没有值")); } } // Keep the console window open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); } } //output //Magnus is owned by Daisy //Terry is owned by Barley //Terry is owned by Boots //Terry is owned by Blue Moon //Charlotte is owned by Whiskers //Arlene is owned by 没有值