Skip to content

LINQ in C# with Practical Examples

LINQ (Language Integrated Query) lets you query data directly in C#: filter it, sort it, group it, join it and calculate totals, using the same syntax whether the data is a List in memory, a database table through Entity Framework Core, or an XML file. Instead of writing loops with if conditions and temporary lists, you describe what you want, and LINQ does the looping for you.

This tutorial uses one practical example throughout: a list of six employees. Every query on this page was run on .NET 10, and the output shown under each query is the real result. For the theory of query syntax and the full list of operators, see LINQ Queries.

Compare it with SQL: in SQL Server you write SELECT Name FROM Employees WHERE Department = 'IT'. With LINQ you write the same idea in C#: employees.Where(e => e.Department == "IT").Select(e => e.Name), with IntelliSense and compile-time checking.

The sample data

An Employee class with six records. GetAllEmployees() returns them as a List<Employee>:

internal class Employee
 {
     public int Id { get; set; }
     public string Name { get; set; } = "";
     public string Department { get; set; } = "";
     public string City { get; set; } = "";
     public decimal Salary { get; set; }
     public DateTime JoinDate { get; set; }

     public List<Employee> GetAllEmployees()
     {
         var employees = new List<Employee>
         {
             new() { Id = 1, Name = "Rahul", Department = "IT", City = "Delhi", Salary = 80000, JoinDate = new DateTime(2020,1,10)},
             new() { Id = 2, Name = "Anita", Department = "HR", City = "Mumbai", Salary = 60000, JoinDate = new DateTime(2019,5,20)},
             new() { Id = 3, Name = "Karan", Department = "IT", City = "Bangalore", Salary = 95000, JoinDate = new DateTime(2021,3,5)},
             new() { Id = 4, Name = "Sneha", Department = "Finance", City = "Delhi", Salary = 70000, JoinDate = new DateTime(2018,11,1)},
             new() { Id = 5, Name = "Vikas", Department = "IT", City = "Pune", Salary = 50000, JoinDate = new DateTime(2022,6,15)},
             new() { Id = 6, Name = "Anupriya", Department = "HR", City = "Khandwa", Salary = 70000, JoinDate = new DateTime(2019,5,20)},
         };
         return employees;
     }
 }
IdNameDepartmentCitySalaryJoinDate
1RahulITDelhi8000010 Jan 2020
2AnitaHRMumbai6000020 May 2019
3KaranITBangalore950005 Mar 2021
4SnehaFinanceDelhi700001 Nov 2018
5VikasITPune5000015 Jun 2022
6AnupriyaHRKhandwa7000020 May 2019

Load the list once; every example below queries this employees variable:

List<Employee> employees = new List<Employee>();
Employee employee = new Employee();
employees = employee.GetAllEmployees();

LINQ's methods live in the System.Linq namespace. In .NET 6 and later it's included automatically through implicit usings; in older projects add using System.Linq; at the top of the file.

What is a LINQ operator?

A LINQ operator is a method that does one job on a sequence of data: Where filters, Select transforms, OrderBy sorts, Sum adds up. Microsoft calls them the standard query operators. They are extension methods on IEnumerable<T> (for in-memory collections) and IQueryable<T> (for databases), which is why any list or array suddenly has a .Where() method.

Most operators return another sequence, so you can chain them like a pipeline: filter, then sort, then pick columns. Each step's output is the next step's input.

CategoryOperatorsWhat they do
FilteringWhereKeep only items that match a condition
ProjectionSelect, SelectManyTurn each item into a new shape
SortingOrderBy, OrderByDescending, ThenBy, ThenByDescendingOrder the items
ElementFirst, FirstOrDefault, Single, SingleOrDefault, Last, ElementAtReturn one item
QuantifierAny, All, ContainsAnswer yes/no questions
AggregationCount, Sum, Average, Min, Max, AggregateCalculate one value
GroupingGroupByPut items into groups by a key
SetDistinct, Union, Intersect, ExceptRemove duplicates or combine sequences
PartitioningSkip, Take, SkipWhile, TakeWhileTake a slice, for example one page
JoinJoin, GroupJoinCombine two sequences on a matching key
ConversionToList, ToArray, ToDictionaryTurn the result into a concrete collection

Two ways to write LINQ

Type 1: Method syntax

var itEmployees = employees.Where(e => e.Department == "IT");

Type 2: Query syntax

var itEmployees =
    from e in employees
    where e.Department == "IT"
    select e;
Output (both)
1 Rahul IT 80000
3 Karan IT 95000
5 Vikas IT 50000
  • Method syntax calls the operators directly. e => e.Department == "IT" is a lambda expression: "for each employee e, return true if the department is IT". It's the most common style, and every operator is available.
  • Query syntax looks like SQL (from ... where ... select). The compiler converts it to method calls, so both produce exactly the same result and performance. It's often easier to read for joins and let. Operators such as Count, First or Take have no query keyword, so you mix in method calls for those.

Filtering: Where

Where keeps the items for which the condition (a predicate, a function that returns bool) is true. Conditions can be combined with && and ||, like e.Department == "IT" && e.Salary > 60000.

Filtering by a list of values (like SQL IN)

var ids = new[] { 1, 3, 5,9 };

var filtered = employees.Where(e => ids.Contains(e.Id));
Output
1 Rahul
3 Karan
5 Vikas

Id 9 doesn't exist, so it simply matches nothing. With Entity Framework Core this becomes WHERE Id IN (1, 3, 5, 9) in SQL.

Projection: Select

A projection operator changes the shape of each item: instead of whole Employee objects, you get only the parts you need, or a new object. Select is the projection operator; it's the SELECT column list of LINQ. Projection never changes the number of items; it changes what each item looks like.

Type 3: Select one property

var names = employees.Select(e => e.Name);
Output
Rahul
Anita
Karan
Sneha
Vikas
Anupriya

The result is an IEnumerable<string>: just names, no Employee objects.

Type 4: Select into an anonymous type

var result = employees.Select(e => new
{
    e.Name,
    e.Salary
});
Output
{ Name = Rahul, Salary = 80000 }
{ Name = Anita, Salary = 60000 }
{ Name = Karan, Salary = 95000 }
{ Name = Sneha, Salary = 70000 }
{ Name = Vikas, Salary = 50000 }
{ Name = Anupriya, Salary = 70000 }

new { e.Name, e.Salary } creates an anonymous type: a class the compiler generates for you with two read-only properties, Name and Salary. It's perfect for shaping data inside a method. To return the result from a method, or pass it to a Razor view, project into a named class (a DTO or ViewModel) instead: Select(e => new EmployeeSalaryDto { Name = e.Name, Salary = e.Salary }).

SelectMany: flatten nested collections

var numbers = new[]
{
    new[] {1,2},
    new[] {3,4}
};

var flat = numbers.SelectMany(x => x);
Output
1, 2, 3, 4

Select(x => x) would return two arrays (a list of lists). SelectMany opens each inner collection and returns all their items as one flat sequence. Real uses: all order lines of all orders, all skills of all employees.

Sorting: OrderBy and ThenBy

Type 5: sort by department, then by highest salary

var sorted =
    employees.OrderBy(e => e.Department)
             .ThenByDescending(e => e.Salary);
Output
Finance  Sneha     70000
HR       Anupriya  70000
HR       Anita     60000
IT       Karan     95000
IT       Rahul     80000
IT       Vikas     50000

OrderBy sorts by the first key (department A to Z). ThenByDescending sorts within each department by salary, highest first. Don't write a second OrderBy instead of ThenBy: it would re-sort the whole list and throw away the first ordering. LINQ sorting is stable, so items with equal keys keep their original order.

Element operators: First, Single and friends

Element operators return one item instead of a sequence. They differ in what happens when there are no matches, or more than one. There is no "Mech" department in our data, so this shows the difference clearly:

//type 6
var firstIT = employees.First(e => e.Department == "Mech");
//type 7
var firstIT = employees.Single(e => e.Department == "Mech");
//type 8
var firstIT = employees.FirstOrDefault(e => e.Department == "Mech");
//type 9
var firstIT = employees.SingleOrDefault(e => e.Department == "Mech");
Output (each run separately)
First(Mech):           InvalidOperationException: Sequence contains no matching element
Single(Mech):          InvalidOperationException: Sequence contains no matching element
FirstOrDefault(Mech):  null
SingleOrDefault(Mech): null

And when there are matches:

var firstIT1 = employees.First(e => e.Department == "IT");
Console.WriteLine(firstIT1.Name); // Rahul

var emp = employees.FirstOrDefault(e => e.Id == 3);

var firstLegal = employees.FirstOrDefault(e => e.Department == "Legal");
Console.WriteLine(firstLegal == null ? "Not found" : firstLegal.Name); // Not found

var hrEmployee = employees.Single(e => e.Department == "HR");
Console.WriteLine(hrEmployee.Name);

// Throws exception if multiple matches
employees.Single(e => e.Department == "IT"); // InvalidOperationException

var legalEmp = employees.SingleOrDefault(e => e.Department == "Legal");
Console.WriteLine(legalEmp == null ? "Not found" : legalEmp.Name); // Not found

// Still throws if multiple matches
employees.SingleOrDefault(e => e.Department == "IT"); // InvalidOperationException
Output
First(IT):            Rahul
FirstOrDefault(Id 3): Karan
FirstOrDefault(Legal): Not found
Single(HR):           InvalidOperationException: Sequence contains more than one matching element
Single(IT):           InvalidOperationException: Sequence contains more than one matching element
SingleOrDefault(Legal): Not found
SingleOrDefault(IT):  InvalidOperationException: Sequence contains more than one matching element

Watch out: Single(e => e.Department == "HR") does not return Anita. Our data has two HR employees, Anita and Anupriya, so Single throws. That's exactly its job: it guarantees there is exactly one match. With one match it works: employees.Single(e => e.Department == "Finance") returns Sneha.

OperatorNo matchOne matchSeveral matches
FirstThrowsReturns itReturns the first
FirstOrDefaultReturns null (default)Returns itReturns the first
SingleThrowsReturns itThrows
SingleOrDefaultReturns null (default)Returns itThrows

Which to use? FirstOrDefault for "find this item if it exists" (then check for null). Single or SingleOrDefault when there must never be more than one, like looking up by a unique email: if a duplicate exists, you want the error. For value types, "default" means 0 or false, not null.

Last and ElementAt

var lastIT = employees.Last(e => e.Department == "IT");
Console.WriteLine(lastIT.Name); // Vikas

var lastLegal = employees.LastOrDefault(e => e.Department == "Legal");
Console.WriteLine(lastLegal == null ? "Not found" : lastLegal.Name); // Not found

var secondEmployee = employees.ElementAt(1);
Console.WriteLine(secondEmployee.Name); // Anita

employees.ElementAt(10); // ArgumentOutOfRangeException

var safeEmployee = employees.ElementAtOrDefault(10);
Console.WriteLine(safeEmployee == null ? "Not found" : safeEmployee.Name); // Not found
Output
Vikas
Not found
Anita
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')
Not found

ElementAt uses a zero-based position: ElementAt(1) is the second employee.

Quantifiers and aggregates

bool hasHighSalary = employees.Any(e => e.Salary > 900000);

bool allFromDelhi = employees.All(e => e.City == "Delhi");
int countIT = employees.Count(e => e.Department == "IT");

decimal totalSalary = employees.Sum(e => e.Salary);

decimal avgSalary = employees.Average(e => e.Salary);

decimal maxSalary = employees.Max(e => e.Salary);
Output
hasHighSalary = False
allFromDelhi  = False
countIT       = 3
totalSalary   = 425000
avgSalary     = 70833.333333333333333333333333
maxSalary     = 95000
  • Any: is there at least one match? Nobody earns over 9,00,000, so False. (Any(e => e.Salary > 90000) returns True, for Karan.) Prefer Any() over Count() > 0: it stops at the first match.
  • All: does every item match? Only Rahul and Sneha are in Delhi, so False.
  • Count, Sum, Average, Max, Min work like SQL's aggregate functions. Average on decimal keeps full decimal precision, as the long result shows; round it for display with Math.Round(avgSalary, 2).

Aggregate: build your own calculation

decimal total =
    employees.Aggregate(0m, (sum, e) => sum + e.Salary);
Output
425000

Aggregate starts with a seed value (0m, a decimal zero) and applies the function to each item, carrying the running result. It produces the same 425000 as Sum; use it for custom accumulations that have no built-in operator, such as building a comma-separated string.

Grouping: GroupBy

var grouped =
    employees.GroupBy(e => e.Department)
             .Select(g => new
             {
                 Department = g.Key,
                 Count = g.Count(),
                 AvgSalary = g.Average(x => x.Salary)
             });
Output
{ Department = IT, Count = 3, AvgSalary = 75000 }
{ Department = HR, Count = 2, AvgSalary = 65000 }
{ Department = Finance, Count = 1, AvgSalary = 70000 }

GroupBy returns a sequence of groups. Each group g has a Key (the department) and is itself a collection of that department's employees, so you can call Count() or Average() on it. It's the LINQ equivalent of SQL's GROUP BY. Groups appear in the order their key is first met in the data (IT, then HR, then Finance), not alphabetically; add OrderBy(g => g.Key) if you need that.

Set operators: Distinct and Union

var cities = employees.Select(e => e.City).Distinct();
Output
Delhi
Mumbai
Bangalore
Pune
Khandwa

Six employees, five cities: Delhi appears once.

var delhi = employees.Where(e => e.City == "Delhi");

var pune = employees.Where(e => e.City == "Pune");

var union = delhi.Union(pune);
Output
Rahul Delhi
Sneha Delhi
Vikas Pune

Union combines two sequences and removes duplicates; Concat combines them and keeps duplicates. For class objects like Employee, "duplicate" means the same object reference unless the class overrides Equals and GetHashCode, or you use UnionBy(e => e.Id). It works here because both queries return objects from the same list.

Partitioning: Skip, Take and SkipWhile (paging)

var page1 = employees.Skip(2).Take(1);
var page1 = employees.SkipWhile(x=>x.Salary>90000).Take(2);
var page2 = employees.Skip(2).Take(2);
Output (each run separately)
Skip(2).Take(1):            Karan
SkipWhile(>90000).Take(2):  Rahul, Anita
Skip(2).Take(2):            Karan, Sneha
  • Skip(n) skips the first n items; Take(n) returns the next n. Together they implement paging: page p with size s is Skip((p - 1) * s).Take(s).
  • SkipWhile skips items while the condition is true, and stops checking at the first item where it's false. The first employee, Rahul (80000), is already not above 90000, so nothing is skipped and Take(2) returns Rahul and Anita. Karan (95000) is never skipped because skipping had already stopped. By contrast, SkipWhile(x => x.Salary < 90000) returned Karan, Sneha, Vikas, Anupriya: it skipped Rahul and Anita, then stopped at Karan.
  • Always sort before paging (OrderBy(...).Skip(...).Take(...)); without a defined order, pages from a database can overlap or skip rows.

Joining two collections

var departments = new[]
{
    new { DeptName = "IT", Manager = "Rohit" },
    new { DeptName = "HR", Manager = "Neha" }
};
var joinResult =
    from e in employees
    join d in departments
      on e.Department equals d.DeptName
    select new
    {
        e.Name,
        e.Department,
        d.Manager
    };
Output
{ Name = Rahul, Department = IT, Manager = Rohit }
{ Name = Anita, Department = HR, Manager = Neha }
{ Name = Karan, Department = IT, Manager = Rohit }
{ Name = Vikas, Department = IT, Manager = Rohit }
{ Name = Anupriya, Department = HR, Manager = Neha }

join ... on ... equals is an inner join: Sneha (Finance) is missing because there is no Finance department in the list, just like an INNER JOIN in SQL. In query syntax you must write equals, not ==. For a left join, use join ... into with DefaultIfEmpty(), or the new LeftJoin operator in .NET 10.

Conversion: ToList and ToDictionary

var list = employees.ToList();

var dict = employees.ToDictionary(e => e.Id);
Output
list.Count  = 6
dict[3].Name = Karan

ToDictionary builds a dictionary for very fast lookups by key. The key must be unique: employees.ToDictionary(e => e.Department) fails with ArgumentException: An item with the same key has already been added. Key: IT. Use ToLookup or GroupBy when keys repeat.

Practical patterns: ranking and comparisons

These patterns answer real reporting questions, the same ones you would solve in SQL with ROW_NUMBER and LAG.

Rank employees by salary

var ranked =
    employees
        .OrderByDescending(e => e.Salary)
        .Select((e, index) => new
        {
            Rank = index + 1,
            e.Name,
            e.Salary
        });

foreach (var item in ranked)
{
    Console.WriteLine(item.Rank);
    Console.WriteLine(item.Name);
    Console.WriteLine(item.Salary);
}
Output
1
Karan
95000
2
Rahul
80000
3
Sneha
70000
4
Anupriya
70000
5
Anita
60000
6
Vikas
50000

This Select overload gives you each item's position (index, starting at 0) as well as the item, so index + 1 becomes the rank. Notice Sneha and Anupriya both earn 70000 but get ranks 3 and 4: this is SQL's ROW_NUMBER, not RANK. For true ties, compute the rank as "1 + number of employees earning more".

Rank per department

var perDeptRank =
    employees
        .GroupBy(e => e.Department)
        .SelectMany(g =>
            g.OrderByDescending(e => e.Salary)
             .Select((e, index) => new
             {
                 Department = g.Key,
                 Rank = index + 1,
                 e.Name,
                 e.Salary
             }));
Output
{ Department = IT, Rank = 1, Name = Karan, Salary = 95000 }
{ Department = IT, Rank = 2, Name = Rahul, Salary = 80000 }
{ Department = IT, Rank = 3, Name = Vikas, Salary = 50000 }
{ Department = HR, Rank = 1, Name = Anupriya, Salary = 70000 }
{ Department = HR, Rank = 2, Name = Anita, Salary = 60000 }
{ Department = Finance, Rank = 1, Name = Sneha, Salary = 70000 }

Group by department, rank inside each group, then SelectMany flattens the groups back into one list. It's the LINQ version of ROW_NUMBER() OVER (PARTITION BY Department ORDER BY Salary DESC).

Top N per department

var top2PerDept =
    employees
        .GroupBy(e => e.Department)
        .SelectMany(g =>
            g.OrderByDescending(e => e.Salary)
             .Take(2));
Output
IT Karan 95000
IT Rahul 80000
HR Anupriya 70000
HR Anita 60000
Finance Sneha 70000

Vikas, the third IT employee, is left out. Finance has only one employee, so it returns one.

Previous row (like SQL LAG)

var ordered = employees.OrderBy(e => e.JoinDate).ToList();

var withPrev =
    ordered.Select((e, i) => new
    {
        e.Name,
        e.Salary,
        PrevSalary = i > 0 ? ordered[i - 1].Salary : (decimal?)null
    });
Output
{ Name = Sneha, Salary = 70000, PrevSalary =  }
{ Name = Anita, Salary = 60000, PrevSalary = 70000 }
{ Name = Anupriya, Salary = 70000, PrevSalary = 60000 }
{ Name = Rahul, Salary = 80000, PrevSalary = 70000 }
{ Name = Karan, Salary = 95000, PrevSalary = 80000 }
{ Name = Vikas, Salary = 50000, PrevSalary = 95000 }

Employees ordered by join date, each with the salary of the person who joined before them. ToList() is important here: it lets us read ordered[i - 1] by position. The first employee has no previous row, so PrevSalary is null, which is why it's declared decimal?.

Salary difference from the department average (let)

var query =
    from e in employees
    let avgDeptSalary =
        employees.Where(x => x.Department == e.Department)
                 .Average(x => x.Salary)
    select new
    {
        e.Name,
        e.Department,
        Diff = e.Salary - avgDeptSalary
    };
Output
{ Name = Rahul, Department = IT, Diff = 5000 }
{ Name = Anita, Department = HR, Diff = -5000 }
{ Name = Karan, Department = IT, Diff = 20000 }
{ Name = Sneha, Department = Finance, Diff = 0 }
{ Name = Vikas, Department = IT, Diff = -25000 }
{ Name = Anupriya, Department = HR, Diff = 5000 }

let stores an intermediate value (here, the average salary of the employee's department) so you can use it in select. Karan earns 20000 above the IT average of 75000; Vikas earns 25000 below it. For large lists, calculate the averages once with GroupBy and a dictionary, because this version recalculates the department average for every employee.

Deferred execution: when does a query run?

A LINQ query like employees.Where(...) doesn't run when you write it. It's only a recipe; it runs each time you enumerate it (with foreach, ToList(), Count() and so on). This is called deferred execution:

var itQuery = employees.Where(e => e.Department == "IT");

employees.Add(new Employee { Id = 7, Name = "Meera", Department = "IT", City = "Indore", Salary = 65000, JoinDate = new DateTime(2023, 2, 1) });

Console.WriteLine(itQuery.Count());
Output
4

The query was written when there were three IT employees, but it counts 4, because it runs at the moment Count() is called and sees Meera. Operators that return a single value (Count, Sum, First) and conversion operators (ToList, ToArray, ToDictionary) run immediately. Call ToList() when you want to run a query once and reuse the result.

LINQ in ASP.NET Core with Entity Framework Core

The same operators work on database tables through EF Core, for example in a controller:

var itEmployees = await _context.Employees
    .Where(e => e.Department == "IT")
    .OrderByDescending(e => e.Salary)
    .Select(e => new { e.Name, e.Salary })
    .ToListAsync();
  • On a DbSet, the query is an IQueryable: EF Core translates the whole chain into one SQL query and runs it in the database. Only the matching rows and selected columns come back.
  • On a List, it's an IEnumerable: the query runs in memory in your application.
  • Filter and project before ToList(). Calling ToList() first downloads the whole table and filters it in C#, which is a common cause of slow pages. See IEnumerable vs List.

Interview questions

1. What is LINQ?

Language Integrated Query: a set of C# language features and standard query operators for querying any data source (collections, databases, XML) with one consistent, strongly typed syntax.

2. What is the difference between query syntax and method syntax?

Query syntax looks like SQL (from ... where ... select); method syntax chains extension methods with lambdas. The compiler turns query syntax into method calls, so results and performance are identical. Some operators (Count, First, Take) exist only as methods.

3. What is a projection operator?

An operator that transforms each item into a new shape. Select maps each item to a property, an anonymous type or a DTO; SelectMany maps each item to a collection and flattens the results into one sequence.

4. What is the difference between First, FirstOrDefault, Single and SingleOrDefault?

First returns the first match and throws if there is none; FirstOrDefault returns the default (null) instead of throwing. Single returns the only match and throws if there are zero or several; SingleOrDefault returns the default for zero but still throws for several.

5. What is the difference between Select and SelectMany?

Select returns one result per item, so a property that is a collection gives you a collection of collections. SelectMany flattens those inner collections into a single sequence: [[1,2],[3,4]] becomes 1, 2, 3, 4.

6. What is deferred execution?

A query that returns a sequence is not executed when it's defined, but each time it's enumerated. Changes to the source before enumeration are included. Aggregates and ToList/ToArray execute immediately.

7. What is the difference between IEnumerable and IQueryable in LINQ?

IEnumerable queries run in memory using C# delegates. IQueryable queries are built as expression trees that a provider such as EF Core translates into SQL and runs in the database.

8. What is the difference between Any() and Count() > 0?

Both check whether matches exist, but Any() stops at the first match, while Count() counts every item. Any() is faster and clearer.

9. What is the difference between Skip/Take and SkipWhile/TakeWhile?

Skip and Take work by count. SkipWhile and TakeWhile work by condition, and stop checking as soon as the condition is false for one item, so later items that would match are not skipped.

Summary

  • LINQ queries collections and databases in C#, with method syntax (lambdas) or query syntax (from ... select).
  • Operators are extension methods that do one job each: filter (Where), project (Select, SelectMany), sort (OrderBy, ThenBy), group, join, aggregate, page.
  • First/FirstOrDefault return the first match; Single/SingleOrDefault demand exactly one and throw on duplicates.
  • The indexed Select overload enables ranking; GroupBy plus SelectMany gives per-group ranking and top N.
  • Queries are deferred until enumerated; with EF Core, filter and project before ToList so the work happens in SQL.

Related: LINQ Queries (theory), ViewModel in ASP.NET Core and AutoMapper.