42

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

6 回答 6

76

我认为如果你想使用扩展方法,你需要使用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();
于 2009-02-08T06:04:55.533 回答
17

您需要将连接的对象放入一个集合中,然后像JPunyon 所说的那样应用 DefaultIfEmpty:

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 };
List<Person> people = new List<Person> { magnus, terry, charlotte };
List<Pet> pets = new List<Pet>{barley};

var results =
    from person in people
    join pet in pets on person.Name equals pet.Owner.Name into ownedPets
    from ownedPet in ownedPets.DefaultIfEmpty(new Pet())
    orderby person.Name
    select new { OwnerName = person.Name, ownedPet.Name };


foreach (var item in results)
{
    Console.WriteLine(
        String.Format("{0,-25} has {1}", item.OwnerName, item.Name ) );
}

输出:

Adams, Terry              has Barley
Hedlund, Magnus           has
Weiss, Charlotte          has
于 2009-02-08T06:50:38.250 回答
5

我遇到同样的问题时出现以下错误消息:

join 子句中的表达式之一的类型不正确。调用“GroupJoin”时类型推断失败。

当我使用相同的属性名称时解决了,它起作用了。

(...)

join enderecoST in db.PessoaEnderecos on 
    new 
      {  
         CD_PESSOA          = nf.CD_PESSOA_ST, 
         CD_ENDERECO_PESSOA = nf.CD_ENDERECO_PESSOA_ST 
      } equals 
    new 
    { 
         enderecoST.CD_PESSOA, 
         enderecoST.CD_ENDERECO_PESSOA 
    } into eST

(...)

于 2009-03-02T17:08:39.487 回答
3

这是一篇很好的博客文章,刚刚由 Fabrice(LINQ in Action 的作者)发布,其中涵盖了我提出的问题中的材料。我把它放在这里供参考,因为问题的读者会发现这很有用。

将 LINQ 查询从查询​​语法转换为方法/运算符语法

于 2009-02-10T19:49:20.387 回答
2

使用 DefaultIfEmpty() 方法可以在 LINQ 中进行左连接。不过,我没有适合您的情况的确切语法...

实际上,我认为如果您只是在查询中将 pets.DefaultIfEmpty() 更改为它可能会起作用......

编辑:我真的不应该在很晚的时候回答事情......

于 2009-02-08T05:30:03.873 回答
0

如果你真的有一个数据库,这是最简单的方法:

var lsPetOwners = ( from person in context.People
                    from pets in context.Pets
                        .Where(mypet => mypet.Owner == person.ID) 
                        .DefaultIfEmpty()
                     select new { OwnerName = person.Name, Pet = pets.Name }
                   ).ToList();
于 2015-08-18T08:21:43.503 回答