Query Syntax vs Method Syntax
LINQ can also be written in query syntax, from ... where ... orderby ... select, which reads like SQL. The compiler turns it into the same method calls. Method syntax is more common, and some methods, such as Count and First, have no query keyword.
Journeyman · C# · Updated
After this lesson you can
- Rewrite a LINQ query between query syntax (from, where, orderby, select) and method syntax
Key takeaways
- Query syntax,
from name in names ... select ..., compiles to the same method calls as method syntax, so the two run exactly the same way. - Each keyword matches a method;
whereisWhere,orderbyisOrderBy,selectisSelectandgroup ... byisGroupBy. - Unlike SQL, query syntax puts
selectlast, and a query must end withselect(orgroup). - Methods with no keyword, such as
CountorToList, are called on the query wrapped in parentheses. - Write method syntax by default, and be ready to read query syntax in someone else's code.
Everything so far has been method syntax: a chain of method calls with lambdas. LINQ has a second way to write the same query, query syntax, which looks a lot like SQL.
The same query, two ways
List<string> names = new List<string> { "Olivia", "Ethan", "Sophia", "Liam", "Emma", "Noah", "Ava", "Jackson" };
List<string> methodSyntax = names
.Where(name => name.Length > 4)
.OrderBy(name => name)
.Select(name => name.ToUpper())
.ToList();
List<string> querySyntax =
(from name in names
where name.Length > 4
orderby name
select name.ToUpper())
.ToList();
Console.WriteLine(string.Join(", ", methodSyntax));
Console.WriteLine(string.Join(", ", querySyntax));
ETHAN, JACKSON, OLIVIA, SOPHIA
ETHAN, JACKSON, OLIVIA, SOPHIA
Query syntax:
- starts with
from name in names: for eachnameinnames.nameplays the part of the lambda's parameter, for the whole query. - uses keywords instead of methods:
where,orderby,select, with no lambdas or arrows. - must end with
select(orgroup).
The compiler turns query syntax into the very same method calls, so the two run exactly the same way.
Side by side
| Query syntax | Method syntax |
|---|---|
from p in menu |
menu |
where p.Price < 3.00m |
.Where(p => p.Price < 3.00m) |
orderby p.Price |
.OrderBy(p => p.Price) |
orderby p.Price descending |
.OrderByDescending(p => p.Price) |
orderby p.Category, p.Name |
.OrderBy(p => p.Category).ThenBy(p => p.Name) |
select p.Name |
.Select(p => p.Name) |
group p by p.Category |
.GroupBy(p => p.Category) |
One difference from SQL: in query syntax, select comes last, after from. That's so that by the time you type p., Visual Studio already knows what p is and can suggest its properties.
Mixing the two
Many methods have no keyword: Count, Sum, First, Take, Distinct, ToList. To use them with query syntax, put the query in parentheses and call the method on it, as .ToList() was above:
List<int> scores = new List<int> { 72, 95, 48, 88, 61 };
int passes = (from score in scores
where score >= 60
select score).Count();
int passesToo = scores.Count(score => score >= 60);
Console.WriteLine( quot;{passes} {passesToo}");
4 4
Which to use?
Both are correct, and you'll meet both. Most C# code, and this course, uses method syntax:
- every LINQ method works in it, so there's no switching between styles,
- a short query is often a single line:
scores.Count(score => score >= 60), - the lambdas are the same ones you pass to
FindAll,Sortand, later, to ASP.NET Core and Entity Framework Core.
Query syntax shines for long queries with joins and grouping, where it can read more clearly. Choose one style per query, and be ready to read the other.
Do it: list the bakery case in query syntax
The café's bakery case has a card that lists its items, most expensive first. A teammate wrote the café's other queries in query syntax, so this one should match.
The method gets one value:
menu: the café's products, aList<Product>. EachProducthas aName, aCategoryand aPrice.
Program.cs already has the Product class, and a menu holding the café's six products from Common LINQ Methods. For example, BakeryCard(menu) works like this:
| Step | Products |
|---|---|
| The menu | Coffee (Drinks, 3.50), Tea (Drinks, 2.75), Juice (Drinks, 4.00), Croissant (Bakery, 3.75), Muffin (Bakery, 2.50), Bagel (Bakery, 2.25) |
| Only the bakery items | Croissant (3.75), Muffin (2.50), Bagel (2.25) |
| Most expensive first | Croissant (3.75), Muffin (2.50), Bagel (2.25) (already in this order here; the tests also add an item that isn't) |
| Just the names | "Croissant", "Muffin", "Bagel" |
So BakeryCard(menu) returns a list of "Croissant", "Muffin" and "Bagel", in that order.
Your job: write the method List<string> BakeryCard(List<Product> menu) with a query in query syntax: from, where, orderby and select.
- Keep only the products whose
Categoryis"Bakery". - Put them in order by
Price, most expensive first. - Give back their names, as a
List<string>. - When the menu has no bakery items, return an empty list. That includes an empty menu.
The tests check the names the method gives back. Writing the query in query syntax is your practice.
Practiced live on the lesson page: write the C# right there and check it.
Check yourself
1 question to try on the lesson page.
So what
from ... where ... orderby ... select and .Where().OrderBy().Select() are two spellings of one query. Write method syntax by default, and when you meet query syntax in someone else's code, translate it in your head keyword by keyword.