52

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.

Foggzie
  • 9,691
  • 1
  • 31
  • 48
Manvinder
  • 4,495
  • 16
  • 53
  • 100
  • Just see here: http://stackoverflow.com/questions/3435485/linq-group-by-multiple-tables – aF. Jan 04 '12 at 09:48
  • Thanks, i've already seen that, but Concat does not seems like a good option, moreover the structure for both of my table is too different, so this is not gonna work for me, – Manvinder Jan 04 '12 at 09:50

3 Answers3

79

For grouping multiple tables you can do as:

group new { r,s } by new { r.SpaceID, s.SpaceCode }
Pankaj Tiwari
  • 1,378
  • 11
  • 13
41

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

Arion
  • 31,011
  • 10
  • 70
  • 88
0

You can use the following command.

grp.Sum(x => x.r.Col1)

It works well.

4b0
  • 21,981
  • 30
  • 95
  • 142
Xiao
  • 1