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
Author by
Manvinder
Updated on July 09, 2022Comments
-
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ý over 12 yearsSelect part should be:
select new { Count = grp.Count(), grp.Key.SpaceID, grp.Key.SpaceCode }
-
Buggieboy over 11 years@Arion: Petr Behensky's correction still doesn't appear in your solution.
-
Admin almost 8 yearsIn this case, how to get other fields of r, s in select new? grp.r or grp.s seem not working.
-
Pablo over 3 yearsHow can I sum others columns from
r
, ors
in theselect new
? -
Pablo over 3 yearsHow can I sum a column like
grp.Sum(x => x.Col1)
? I'm trying but it's not working