gpt4 book ai didi

c# - LINQ 内连接与左连接

转载 作者:IT王子 更新时间:2023-10-29 03:55:12 25 4
gpt4 key购买 nike

我尝试使用扩展语法在我拥有的两个列表上使用 LINQ 创建左连接。以下内容来自 Microsoft 帮助,但我对其进行了修改以显示宠物列表没有任何元素。我最终得到的是一个包含 0 个元素的列表。我认为这是因为正在进行内部连接。我最终想要的是一个包含 3 个元素(3 个 Person 对象)的列表,其中为缺失的元素填充了空数据。即左连接。这可能吗?

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

var query =
people.GroupJoin(pets,
person => person,
pet => pet.Owner,
(person, petCollection) =>
new { OwnerName = person.Name,
Pet = PetCollection.Select( p => p.Name )
.DefaultIfEmpty() }
).ToList();

您可能需要尝试使用选择表达式。如果您有一对多关系,我不确定它是否会给您想要的。

我认为使用 LINQ 查询语法会更容易一些

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();

关于c# - LINQ 内连接与左连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/525194/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com