Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

C# Tutorial

C# HOME C# Intro C# Get Started C# Syntax C# Output C# Comments C# Variables C# Data Types C# Type Casting C# User Input C# Operators C# Math C# Strings C# Booleans C# If...Else C# Switch C# While Loop C# For Loop C# Break/Continue C# Arrays

C# Methods

C# Methods C# Method Parameters C# Method Overloading C# Scope C# Recursion

C# Classes

C# OOP C# Classes/Objects C# Class Members C# Constructors C# this Keyword C# Access Modifiers C# Properties C# Static C# Inheritance C# Polymorphism C# Abstraction C# Interface C# Enums C# Structs

C# Errors

C# Errors C# Debugging C# Exceptions

C# Data Structures

C# Data Structures C# List C# Dictionary C# HashSet C# Stack C# Queue

C# Advanced

C# Files C# Date and Time C# Nullable Types C# Generics C# Lambda C# LINQ

C# Cert

C# Certificate

C# How To

C# How Tos

C# Examples

C# Examples C# Compiler C# Exercises C# Quiz C# Practice Problems C# Server C# Syllabus C# Study Plan


C# LINQ


Share

LINQ

When you have a list of data, you often want to ask questions about it. Which scores are 50 or more? What is the total? What are the names in alphabetical order?

You can answer these questions with loops and if statements, but it takes many lines of code. LINQ (Language Integrated Query) gives you methods that answer them in one line.

To use LINQ, include the System.Linq namespace at the top of the file:

Example

using System.Linq;  // Include the namespace that holds LINQ

Here is the total of a list of scores, first with a loop, and then with the LINQ method Sum():

Example

List<int> scores = new List<int> { 45, 80, 62, 30, 95 };

// With a loop
int total = 0;
foreach (int score in scores)
{
  total += score;
}
Console.WriteLine(total);  // 312

// With LINQ
Console.WriteLine(scores.Sum());  // 312

Try it Yourself »

You already used Sum(), Min() and Max() with arrays in the Sort Arrays chapter. LINQ works with both arrays and lists.


Filter With Where()

Where() keeps only the items that match a condition. You write the condition as a lambda, like you learned in the previous chapter:

Example

List<int> scores = new List<int> { 45, 80, 62, 30, 95 };
var passed = scores.Where(s => s >= 50);

foreach (int score in passed)
{
  Console.WriteLine(score);
}

Try it Yourself »

The lambda s => s >= 50 returns true for the scores that are 50 or more, so Where() keeps 80, 62 and 95.

The result of Where() is not a list, but you can loop through it with foreach. We use var, because the real name of the type is long.

To print the results on one line, use string.Join(). It joins the items into one string, with a separator (here ", ") between them:

Example

List<int> scores = new List<int> { 45, 80, 62, 30, 95 };
var passed = scores.Where(s => s >= 50);
Console.WriteLine(string.Join(", ", passed));  // 80, 62, 95

Try it Yourself »


Change Each Item With Select()

Select() runs a lambda on each item, and returns the new values. Here, each name is changed to uppercase letters:

Example

List<string> names = new List<string> { "Liam", "Jenny", "Angie" };
var upper = names.Select(n => n.ToUpper());
Console.WriteLine(string.Join(", ", upper));  // LIAM, JENNY, ANGIE

Try it Yourself »

The original list does not change. names still contains "Liam", "Jenny" and "Angie".



Sort With OrderBy()

OrderBy() sorts the items from low to high (or from A to Z). OrderByDescending() sorts from high to low:

Example

List<string> cars = new List<string> { "Volvo", "BMW", "Ford", "Mazda" };
var sorted = cars.OrderBy(c => c);
Console.WriteLine(string.Join(", ", sorted));  // BMW, Ford, Mazda, Volvo

List<int> scores = new List<int> { 45, 80, 62, 30, 95 };
var highFirst = scores.OrderByDescending(s => s);
Console.WriteLine(string.Join(", ", highFirst));  // 95, 80, 62, 45, 30

Try it Yourself »

The lambda says what to sort by. c => c means "sort by the item itself". To sort the cars by the length of their names, you could write cars.OrderBy(c => c.Length).

Unlike the Sort() method of a List, OrderBy() does not change the original list.


Get One Value

Some LINQ methods return one single value, instead of many items:

Example

List<int> scores = new List<int> { 45, 80, 62, 30, 95 };
Console.WriteLine(scores.Count(s => s >= 50));  // 3
Console.WriteLine(scores.Sum());                // 312
Console.WriteLine(scores.Average());            // 62.4
Console.WriteLine(scores.Min());                // 30
Console.WriteLine(scores.Max());                // 95
Console.WriteLine(scores.First(s => s >= 50));  // 80

Try it Yourself »

MethodDescription
Count()Returns the number of items. With a lambda, it counts only the items that match
Sum()Returns the total of all items
Average()Returns the average value
Min()Returns the lowest value
Max()Returns the highest value
First()Returns the first item. With a lambda, it returns the first item that matches

Chain Methods

You can call LINQ methods one after another. Each method works on the result of the method before it.

Here, Where() keeps the scores that are 50 or more, and then OrderBy() sorts them:

Example

List<int> scores = new List<int> { 45, 80, 62, 30, 95 };
var result = scores.Where(s => s >= 50).OrderBy(s => s);
Console.WriteLine(string.Join(", ", result));  // 62, 80, 95

Try it Yourself »

Methods like Where(), Select() and OrderBy() don't return a List. If you need a real list, for example to add more items with Add(), call ToList() at the end:

Example

List<int> scores = new List<int> { 45, 80, 62, 30, 95 };
List<int> passed = scores.Where(s => s >= 50).ToList();
passed.Add(70);
Console.WriteLine(string.Join(", ", passed));  // 80, 62, 95, 70

Try it Yourself »


Query Syntax

LINQ can also be written in another way, called query syntax. It looks a bit like a sentence:

Example

List<int> scores = new List<int> { 45, 80, 62, 30, 95 };
var passed = from s in scores where s >= 50 select s;
Console.WriteLine(string.Join(", ", passed));  // 80, 62, 95

Try it Yourself »

  • from s in scores takes each item s from the list
  • where s >= 50 keeps the items that match
  • select s says what to return

This gives the same result as scores.Where(s => s >= 50). Use the way you find easier to read. This tutorial uses the methods with lambdas.



Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.