Group Multiple Tables in LINQ

49,160

Solution 1

For grouping multiple tables you can do as:

group new { r,s } by new { r.SpaceID, s.SpaceCode }

Solution 2

this might help:

(
    from r in db.Rider
    join s in db.Spaces
        on r.SpaceID equals s.SpaceID
    group new { r,s } by new { r.SpaceID, s.SpaceCode }
    into grp
    select new
    {
        Count=grp.Count(),
        grp.Key.SpaceID,
        grp.Key.SpaceCode
    }
)

Where db is the database context

Share:
49,160
Manvinder
Author by

Manvinder

Updated on July 09, 2022

Comments

  • Manvinder
    Manvinder almost 2 years

    I have a very simple SQL query:

    SELECT r.SpaceID, Count (*), SpaceCode 
    FROM Rider r JOIN Spaces s 
    ON r.SpaceID = s.SpaceID
    GROUP BY r.SpaceID, s.SpaceCode 
    

    Please note that my group by clause is on multiple tables, I want to do the same in LINQ, I know how to group single table, but about multiple tables I have no idea.

  • Petr Behenský
    Petr Behenský over 12 years
    Select part should be: select new { Count = grp.Count(), grp.Key.SpaceID, grp.Key.SpaceCode }
  • Buggieboy
    Buggieboy over 11 years
    @Arion: Petr Behensky's correction still doesn't appear in your solution.
  • Admin
    Admin almost 8 years
    In this case, how to get other fields of r, s in select new? grp.r or grp.s seem not working.
  • Pablo
    Pablo over 3 years
    How can I sum others columns from r, or s in the select new?
  • Pablo
    Pablo over 3 years
    How can I sum a column like grp.Sum(x => x.Col1)? I'm trying but it's not working