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

 

转载于:https://www.cnblogs.com/dehuachenyunfei/p/7773420.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值