Junior — Middle
What types of LINQ queries do you know and what are their differences?
sobes.tech AI
Answer from AI
In LINQ (Language Integrated Query) in C#, there are two main types of queries:
-
Query syntax — similar to SQL and uses keywords like
from,where,select, etc. This style is more declarative and suitable for complex queries. -
Method syntax — uses chains of extension method calls such as
Where(),Select(),OrderBy(), etc. This style is more flexible and allows the use of lambda expressions.
Differences:
- Query syntax is more readable for those familiar with SQL.
- Method syntax provides more control and capabilities, especially for complex operations.
Example:
// Query syntax
var result1 = from item in collection
where item.Age > 18
select item.Name;
// Method syntax
var result2 = collection.Where(item => item.Age > 18)
.Select(item => item.Name);
Both approaches compile into the same code and can be used interchangeably.