C# Linq Inner Join

后端 未结 3 1129
梦如初夏
梦如初夏 2021-01-11 18:20

I want to select the persons only who are having pets.

when I execute the query

var query = from p in people
                        join
                   


        
3条回答
  •  日久生厌
    2021-01-11 18:44

    That's because you're using join ... into which does a group join. You just want a normal join:

    var query = (from p in people
                 join pts in pets on p equals pts.Owner
                 select p).Distinct();
    

    Alternatively, if you want the people with pets, and their owners, you could do something like:

    var query = pets.GroupBy(pet => pet.Owner)
                    .Select(x => new { Owner = x.Key, Pets = x.ToList() });
    

    That will give a result where you can get each owner and their pets, but only for people who have pets.

    If you want something else, let us know...

    By the way, now would be a good time to learn about object and collection initializers. Here's a simpler way to initialize your people list, for example:

    List people = new List
    {
        new Person { FirstName = "Jon", LastName = "Skeet" },
        new Person { FirstName = "Marc", LastName = "Gravell" },
        new Person { FirstName = "Alex", LastName = "Grover" },
    };
    

    Much more compact :)

    EDIT: A cross join is easy:

    var query = from person in people
                from pet in pets
                select new { person, pet };
    

    Left joins are effectively emulated using group joins. As it sounds like you've got C# in Depth, I suggest you read chapter 11 thoroughly :)

提交回复
热议问题