C# Exception Handling
C# File I/O
C# Delegates and Events
C# Generics
C# Async Programming
C# LINQ Advanced

C# LINQ Advanced

Grouping, joining, flattening, and partitioning with LINQ.

1 - GroupBy

var orders = new[]
{
    new { Product = "Book",   Category = "Education", Price = 29.99m },
    new { Product = "Pen",    Category = "Education", Price = 1.99m  },
    new { Product = "Laptop", Category = "Tech",      Price = 999m   },
    new { Product = "Phone",  Category = "Tech",      Price = 699m   },
};

var byCategory = orders
    .GroupBy(o => o.Category)
    .Select(g => new {
        Category = g.Key,
        Count    = g.Count(),
        Total    = g.Sum(o => o.Price)
    });

foreach (var g in byCategory)
    Console.WriteLine($"{g.Category}: {g.Count} items, ${g.Total}");

2 - Join

var users = new[] { new { Id = 1, Name = "Alice" }, new { Id = 2, Name = "Bob" } };
var posts = new[] { new { UserId = 1, Title = "Hello" }, new { UserId = 1, Title = "World" }, new { UserId = 2, Title = "C# Tips" } };

var userPosts = users.Join(
    posts,
    u => u.Id,
    p => p.UserId,
    (u, p) => new { u.Name, p.Title });

foreach (var up in userPosts)
    Console.WriteLine($"{up.Name}: {up.Title}");

3 - SelectMany — Flattening

var classrooms = new[]
{
    new { Room = "A", Students = new[] { "Alice", "Bob"   } },
    new { Room = "B", Students = new[] { "Carol", "Dave"  } },
};

var allStudents = classrooms.SelectMany(c => c.Students);
Console.WriteLine(string.Join(", ", allStudents));
// Alice, Bob, Carol, Dave

4 - Take, Skip, and Pagination

var data = Enumerable.Range(1, 100);
int page = 2, pageSize = 10;

var pageData = data
    .Skip((page - 1) * pageSize)
    .Take(pageSize);

// 11, 12, 13, ... 20

Note: When working with databases through Entity Framework, LINQ queries are translated to SQL. Calling ToList() or First() triggers the database query. Operations performed after materialisation happen in memory.

-Tip-

C# {"id":46,"topic_id":3,"name":"C# LINQ","slug":"c-linq","image":null,"description":"<p>Language Integrated Query \u2014 query collections, databases, and XML with a unified syntax.<\/p>","icon":null,"class":null,"color":null,"status":0,"order":15,"created_at":"2026-05-03T02:03:02.000000Z","updated_at":"2026-05-03T02:03:02.000000Z"} - List of Contents

Related Tutorials: