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 沒有值

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM