Posts tagged IGrouping
How to Use Grouping in C# LINQ Syntax
Feb 8th
When you started using LINQ, did you think it looked like SQL? I did.
The more I learned LINQ, the more I realized it wasn’t anything like SQL. Take grouping, for example. Because LINQ has a group by statement, and it looks like SQL, I assumed that the syntax for grouping in LINQ would be just like SQL. Ha ha! Wrong! As soon as I tried to use it, I discovered that the LINQ syntax is not only nothing like the SQL equivalent, but the whole grouping concept in LINQ is completely different too.
At first glance, the two syntaxes look slightly similar.
SQL:
select ReportsTo, count(LastName) as NameCount from Employees group by ReportsTo
LINQ (C#):
from employee in Employees group employee by employee.ReportsTo
Ignoring the omission of the select statement from LINQ, and the requirement of a range variable, they do look similar. But looks can be deceiving.
Let me explain why.