Pittfall
Pittfall

Reputation: 2851

How do I select multiple items from a database using LINQ

So I am selecting from a person table and I need to select the group ids of the groups that the person is in. How can I do this.

So far, I have:

var p = (from p in Context.Person
         join g in Context.Group
         on p.PersonId equals g.PersonId
         select new
         {
             Name = p.Name,
             Age  = p.Age,
             groupIds = ?????
         }

So in the group table it will be a primary key of GroupId and PersonId so I need to select all the group ids. How can this be done?

Upvotes: 1

Views: 2623

Answers (2)

Servy
Servy

Reputation: 203815

You want a GroupJoin rather than a Join. The difference is that rather than having all of the related items flattened into a list of pairs, it groups all of the joined items into a sequence:

var query = from p in Context.Person
            join g in Context.Group
            on p.PersonId equals g.PersonId into groups
            select new
            {
                Name = p.Name,
                Age  = p.Age,
                groupIds = groups.Select(g => g.GroupId),
            };

Using query syntax the use of the into keyword in conjunction with a join will result in a GroupJoin instead of a Join.

Upvotes: 6

Davut Gürbüz
Davut Gürbüz

Reputation: 5746

I coded on SO's editor. If I understand right you want Person's groups. Otherwise correct me please.

 var p = from p in Context.Person         
     select new
     {
         Name = p.Name,
         Age  = p.Age,
         groups = from g in Context.Group
                  where p.PersonId == g.PersonId
                  select g.GroupId
     };

Upvotes: 2

Related Questions