LINQ in C#: Types of LINQ in C# with Example
Learn what LINQ is in C#, the different ways to write LINQ queries, and see examples of common LINQ operations.
What is LINQ?
LINQ, or Language Integrated Query, is a set of features that lets you write consistent, readable queries directly against collections, databases, XML, and more.
Query Syntax
Query syntax uses keywords like from, where, and select in a style similar to SQL, making it easy to read for those familiar with database queries.
Method Syntax
Method syntax uses extension methods like Where, Select, and OrderBy chained together with lambda expressions, offering a more compact, fluent style.
Common LINQ Operations
Typical LINQ operations include filtering with Where, projecting with Select, sorting with OrderBy, and aggregating with methods like Sum and Count.
Types of LINQ by Data Source
The same query operators work against very different data sources. What changes is the provider underneath, which decides how the query actually runs.
| Type | Works on | How it runs |
|---|---|---|
| LINQ to Objects | Arrays, List<T>, any IEnumerable<T> | In memory, as C# code |
| LINQ to Entities | Entity Framework Core models | Translated into SQL and sent to the database |
| LINQ to XML | XDocument and XElement | Walks the XML tree in memory |
| LINQ to DataSet | DataTable rows | In memory over ADO.NET data |
| PLINQ | Large in-memory collections | Splits work across CPU cores with AsParallel() |
You may also see LINQ to SQL in older projects. It was the original SQL Server provider and has largely been replaced by Entity Framework.
Same Query, Both Syntaxes
Here is a small list of students. The goal is to find those who scored above 70, sort them by score, and keep only their names.
var students = new List<Student>
{
new("Aman", "CSE", 82),
new("Priya", "ECE", 91),
new("Rahul", "CSE", 64),
new("Sneha", "CSE", 77)
};
// Query syntax
var top1 = from s in students
where s.Score > 70
orderby s.Score descending
select s.Name;
// Method syntax
var top2 = students
.Where(s => s.Score > 70)
.OrderByDescending(s => s.Score)
.Select(s => s.Name);
Console.WriteLine(string.Join(", ", top2)); // Priya, Aman, Sneha
record Student(string Name, string Branch, int Score);
Both versions compile to the same method calls. Query syntax shines when you join or group, while method syntax gives you operators that have no query keyword, such as Take, Skip, Distinct and Any.
Grouping with an aggregate
var byBranch = students
.GroupBy(s => s.Branch)
.Select(g => new { Branch = g.Key, Count = g.Count(), Avg = g.Average(s => s.Score) });
foreach (var b in byBranch)
Console.WriteLine($"{b.Branch}: {b.Count} students, average {b.Avg:F1}");
Deferred Execution and Why It Surprises People
Most LINQ queries do not run when you write them. They run when you loop over the result or call a method like ToList(), Count() or First(). Until then, the variable holds a description of the work.
This has two effects. If the source list changes before you enumerate, the result reflects the new data. And if you enumerate the same query twice, the work happens twice, which can mean two database round trips with Entity Framework. Call ToList() once when you need a stable snapshot you will reuse.
Common LINQ Mistakes and a Quick Checklist
First()on possibly empty data. It throws an exception when nothing matches; useFirstOrDefault()and check for null.- Filtering after
ToList()on a database query. That pulls every row into memory first. KeepWherebefore materialising so the filter becomes SQL. - Using
Count() > 0to test for existence.Any()states the intent and can stop at the first match. - Calling custom C# methods inside an EF Core query. The provider cannot translate them to SQL and will raise an error at runtime.
Before shipping a query, ask: which provider runs it, when is it enumerated, and could the source be empty? Answering those three questions prevents most LINQ bugs.