LINQ 内连接与左连接 [英] LINQ Inner-Join vs Left-Join
问题描述
使用扩展语法我试图在我拥有的两个列表上使用 LINQ 创建一个左连接.以下来自 Microsoft 帮助,但我对其进行了修改以显示宠物列表没有元素.我最终得到的是一个包含 0 个元素的列表.我认为这是因为正在进行内部联接.我想要结束的是一个包含 3 个元素(3 个 Person 对象)的列表,其中为缺失的元素填充了空数据.即左连接.这可能吗?
Using extension syntax I'm trying to create a left-join using LINQ on two lists that I have. The following is from the Microsoft help but I've modified it to show that the pets list has no elements. What I'm ending up with is a list of 0 elements. I assume that this is because an inner-join is taking place. What I want to end up with is a list of 3 elements (the 3 Person objects) with null data filled in for the missing elements. i.e. a Left-Join. Is this possible?
Person magnus = new Person { Name = "Hedlund, Magnus" };
Person terry = new Person { Name = "Adams, Terry" };
Person charlotte = new Person { Name = "Weiss, Charlotte" };
//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 daisy = new Pet { Name = "Daisy", Owner = magnus };
List<Person> people = new List<Person> { magnus, terry, charlotte };
//List<Pet> pets = new List<Pet> { barley, boots, whiskers, daisy };
List<Pet> pets = new List<Pet>();
// Create a list of Person-Pet pairs where
// each element is an anonymous type that contains a
// Pet's name and the name of the Person that owns the Pet.
var query =
people.Join(pets,
person => person,
pet => pet.Owner,
(person, pet) =>
new { OwnerName = person.Name, Pet = pet.Name }).ToList();
推荐答案
我认为如果你想使用扩展方法你需要使用 GroupJoin
I think if you want to use extension methods you need to use the GroupJoin
var query =
people.GroupJoin(pets,
person => person,
pet => pet.Owner,
(person, petCollection) =>
new { OwnerName = person.Name,
Pet = PetCollection.Select( p => p.Name )
.DefaultIfEmpty() }
).ToList();
您可能需要使用选择表达式.我不确定在您拥有一对多关系的情况下它会满足您的需求.
You may have to play around with the selection expression. I'm not sure it would give you want you want in the case where you have a 1-to-many relationship.
我认为使用 LINQ 查询语法更容易一些
I think it's a little easier with the LINQ Query syntax
var query = (from person in context.People
join pet in context.Pets on person equals pet.Owner
into tempPets
from pets in tempPets.DefaultIfEmpty()
select new { OwnerName = person.Name, Pet = pets.Name })
.ToList();
这篇关于LINQ 内连接与左连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!