Search⌘ K
AI Features

Common LINQ Operations II

Learn how to use advanced LINQ methods in C# such as GroupBy, Except, Intersect, Union, and aggregation functions to analyze and manipulate data collections. Understand sequence operations like SelectMany, Zip, DistinctBy, and data partitioning with Skip and Take, enabling you to write concise code for complex data scenarios.

While basic filtering and sorting allow us to extract specific data, real-world applications often require deeper analysis. We frequently need to categorize items, compute statistical summaries, or compare entire datasets against one another. Advanced LINQ extension methods provide a concise, declarative syntax to perform these complex operations without writing manual loops.

Grouping data

Organizing data into categories is a frequent requirement in software development. The GroupBy() method allows us to group elements of a sequence according to a specified key selector function.

We group a list of words by their character count.

C# 14.0
using System.Collections.Generic;
using System.Linq;
var words = new List<string>
{
"apple", "banana", "cherry", "date", "fig", "grape"
};
var groupedByLength = words.GroupBy(word => word.Length);
foreach (var group in groupedByLength)
{
Console.WriteLine($"Words with {group.Key} letters:");
foreach (var word in group)
{
Console.WriteLine($" {word}");
}
}
  • Lines 4–7: We initialize a list of strings to serve as our data source.

  • Line 9: We use the GroupBy() method, providing a lambda expression to use the string's Length property as the grouping key.

  • Line 11: We iterate over the grouped sequence, where each item is an IGrouping object containing a Key.

  • Lines 15–18: We iterate over the group itself to access the individual elements belonging to that key.

Set operations

Set operations generate a new sequence by comparing two existing collections. ...