一尘不染

LINQ内联接vs左联接

c#

使用扩展语法,我试图在我拥有的两个列表上使用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();

阅读 223

收藏
2020-05-19

共1个答案

一尘不染

我认为如果您要使用扩展方法,则需要使用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 Query语法要容易一些

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();
2020-05-19