左外连接Linq没有DefaultIfEmpty

时间:2015-10-05 08:58:19

标签: c# linq

我正在尝试使用此sample

我想要的只是返回:'本书ID = 2。

 new Book{BookID=2, BookNm=".NET and COM for Newbies"},

我只想要那些没有订单的书。

当我删除DefaultIfEmpty()时,它也不起作用。

更新

 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                       
                        where !gj.Any()
                        select person;

我刚试过这段代码,看起来确实有效!

我找回了阿琳的人,她没有宠物!

有人可以证实这是一种已知的方法吗?我刚刚发明了它LOL

1 个答案:

答案 0 :(得分:1)

您误解了左连接的工作原理。 a LEFT JOIN b将返回a中的所有项目,无论它们是否在b中有匹配的项目。如果我正确理解您的问题,您根本不需要加入,因为您不需要bookOrders的任何其他数据。您可以使用LINQ的All扩展方法:

var query = bookList.Where(b => bookOrders.All(o => o.BookId != b.BookId).ToList();

这将返回没有图书订单包含图书ID的所有图书。我的名字基于链接的文章。