articles

home / developersection / articles / introduction to linq in c# with functions

Introduction to LINQ in C# with Functions

Introduction to LINQ in C# with Functions

Anubhav Kumar 1036 22-Apr-2025

LINQ (Language Integrated Query) lets you query collections in C# using readable, concise, and SQL-like syntax. It works on arrays, lists, databases, XML, and more. With LINQ, you can filter, sort, group, and transform data using built-in functions.

LINQ Syntax Styles

C# offers two main styles for writing LINQ:

Syntax Type Example
Query Syntax from n in numbers where n > 5 select n
Method Syntax numbers.Where(n => n > 5)

Common LINQ Functions

Here’s a list of LINQ functions you’ll use most often, with short examples:

1. Where – Filter items by condition

var evenNumbers = numbers.Where(n => n % 2 == 0);

2. Select – Transform each item

var squares = numbers.Select(n => n * n);

3. OrderBy / OrderByDescending – Sort items

var sorted = numbers.OrderBy(n => n);             // Ascending
var desc = numbers.OrderByDescending(n => n);     // Descending

4. First / FirstOrDefault – Get the first item

var firstEven = numbers.First(n => n % 2 == 0);
var orDefault = numbers.FirstOrDefault(n => n > 10); // Returns default (0 for int) if not found

5. Any / All – Boolean checks

bool hasEven = numbers.Any(n => n % 2 == 0);
bool allPositive = numbers.All(n => n > 0);

6. Count / Sum / Max / Min / Average

int count = numbers.Count();
int sum = numbers.Sum();
int max = numbers.Max();
double avg = numbers.Average();

7. Distinct – Remove duplicates

var unique = numbers.Distinct();

8. Take / Skip

var first3 = numbers.Take(3); // First 3 items
var skip2 = numbers.Skip(2);  // Skip first 2

9. GroupBy – Group items by key

var grouped = names.GroupBy(n => n[0]);
foreach (var group in grouped)
{
    Console.WriteLine($"Group: {group.Key}");
    foreach (var name in group)
        Console.WriteLine(name);
}

10. Join – Join two collections

var result = students.Join(
    grades,
    student => student.Id,
    grade => grade.StudentId,
    (student, grade) => new { student.Name, grade.Score }
);

Practical Example

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] numbers = { 5, 2, 9, 1, 5, 6 };

        var query = numbers
                    .Where(n => n > 3)
                    .Distinct()
                    .OrderBy(n => n)
                    .Select(n => $"Number: {n}");

        foreach (var item in query)
        {
            Console.WriteLine(item);
        }
    }
}

Output:

Number: 5  
Number: 6  
Number: 9

LINQ Method Cheat Sheet

Method Purpose
Where() Filter based on condition
Select() Project/transform each element
OrderBy() Sort ascending
OrderByDescending() Sort descending
First() Get the first matching element
FirstOrDefault() Return default if not found
Any() Check if any match exists
All() Check if all match condition
Count() Count elements
Sum() Add all values
Distinct() Remove duplicates
Take(n) Take first n elements
Skip(n) Skip first n elements
GroupBy() Group elements by a key
Join() Combine two data sources by key

Summary

Topic Description
What is LINQ A query language integrated in C#
Works With Arrays, Lists, XML, SQL, JSON
Styles Query and Method Syntax
Functions Powerful methods like Where, Select, GroupBy
Benefits Clean, readable, maintainable code

Next Steps

  1. Learn about deferred execution
  2. Explore LINQ to SQL or Entity Framework
  3. Try writing LINQ queries with complex data types

c# c#  linq 
Updated 22-Apr-2025
Anubhav Kumar

Student

The Anubhav portal was launched in March 2015 at the behest of the Hon'ble Prime Minister for retiring government officials to leave a record of their experiences while in Govt service .

Leave Comment

Comments

Liked By