LINQ Inner-Join vs Left-Join

前端 未结 6 1125
轮回少年
轮回少年 2020-11-27 13:36

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

6条回答
  •  野性不改
    2020-11-27 14:35

    You need to get the joined objects into a set and then apply DefaultIfEmpty as JPunyon said:

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

    Outputs:

    Adams, Terry              has Barley
    Hedlund, Magnus           has
    Weiss, Charlotte          has
    

提交回复
热议问题