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.

Conclusion: LINQ brings a powerful, unified way to query data in C#, and knowing both query syntax and method syntax lets you choose whichever style best fits a given task.

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.

TypeWorks onHow it runs
LINQ to ObjectsArrays, List<T>, any IEnumerable<T>In memory, as C# code
LINQ to EntitiesEntity Framework Core modelsTranslated into SQL and sent to the database
LINQ to XMLXDocument and XElementWalks the XML tree in memory
LINQ to DataSetDataTable rowsIn memory over ADO.NET data
PLINQLarge in-memory collectionsSplits 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; use FirstOrDefault() and check for null.
  • Filtering after ToList() on a database query. That pulls every row into memory first. Keep Where before materialising so the filter becomes SQL.
  • Using Count() > 0 to 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.

Ready to Master C# Programming Course?

Join Uncodemy's hands-on training program with expert mentors and real-world projects.