LINQ (Language-Integrated Query) is a powerful feature in C# that provides a consistent syntax for querying and manipulating data from various sources. LINQ extension methods are a set of methods that extend the functionality of different data types, enabling developers to write expressive and concise queries. In this tutorial, we will explore some commonly used LINQ extension methods in C# with detailed examples to demonstrate their usage and benefits.
Section 1: Filtering Data
1.1. Where
The Where method filters a sequence of elements based on a specified condition. It takes a predicate as an argument and returns a new sequence containing elements that satisfy the condition. Example:
1 2 3 4 5 6 |
int[] numbers = { 1, 2, 3, 4, 5, 6 }; var evenNumbers = numbers.Where(n => n % 2 == 0); // Output: 2, 4, 6 |
1.2. OfType
The OfType method filters a sequence and returns only the elements of a specified type. Example:
1 2 3 4 5 6 |
object[] mixedData = { 1, "apple", 2, "banana", 3, "cherry" }; var strings = mixedData.OfType<string>(); // Output: "apple", "banana", "cherry" |
Section 2: Transforming Data
2.1. Select
The Select method projects each element of a sequence into a new form based on a specified transformation function. Example:
1 2 3 4 5 6 |
string[] names = { "Alice", "Bob", "Charlie" }; var nameLengths = names.Select(name => name.Length); // Output: 5, 3, 7 |
2.2. SelectMany
The SelectMany method projects each element of a sequence to a new sequence and flattens the resulting sequences into one sequence. Example:
1 2 3 4 5 6 |
string[] words = { "Hello", "World" }; var letters = words.SelectMany(word => word.ToCharArray()); // Output: 'H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd' |
Section 3: Sorting Data
3.1. OrderBy and OrderByDescending
The OrderBy and OrderByDescending methods sort the elements of a sequence in ascending or descending order based on a key. Example:
1 2 3 4 5 6 |
string[] fruits = { "cherry", "apple", "banana" }; var sortedFruits = fruits.OrderBy(fruit => fruit); // Output: "apple", "banana", "cherry" |
3.2. ThenBy and ThenByDescending
The ThenBy and ThenByDescending methods are used for secondary sorting. They allow you to specify additional sorting criteria after using OrderBy or OrderByDescending. Example:
1 2 3 4 5 |
var sortedFruits = fruits.OrderBy(fruit => fruit.Length).ThenBy(fruit => fruit); // Output: "apple", "banana", "cherry" |
3.3. Reverse
The Reverse method reverses the order of the elements in a sequence. Example:
1 2 3 4 5 6 |
int[] numbers = { 1, 2, 3, 4, 5 }; var reversedNumbers = numbers.Reverse(); // Output: 5, 4, 3, 2, 1 |
Section 4: Aggregating Data
4.1. Count
The Count method returns the number of elements in a sequence that satisfy a specified condition. Example:
1 2 3 4 5 6 |
int[] numbers = { 1, 2, 3, 4, 5 }; var count = numbers.Count(); // Output: 5 |
4.2. Sum
The Sum method calculates the sum of the elements in a sequence. Example:
1 2 3 4 5 6 |
int[] numbers = { 1, 2, 3, 4, 5 }; var sum = numbers.Sum(); // Output: 15 |
4.3. Average
The Average method calculates the average of the elements in a sequence. Example:
1 2 3 4 5 6 |
int[] numbers = { 1, 2, 3, 4, 5 }; var average = numbers.Average(); // Output: 3 |
4.4. Max and Min
The Max and Min methods return the maximum and minimum values in a sequence, respectively. Example:
1 2 3 4 5 6 7 |
int[] numbers = { 1, 2, 3, 4, 5 }; var max = numbers.Max(); var min = numbers.Min(); // Output: max = 5, min = 1 |
Section 5: Retrieving Elements
5.1. First and FirstOrDefault
The First method returns the first element of a sequence that satisfies a specified condition, while FirstOrDefault returns the first element or a default value if the sequence is empty. Example:
1 2 3 4 5 6 7 |
int[] numbers = { 1, 2, 3, 4, 5 }; var first = numbers.First(); var firstOrDefault = numbers.FirstOrDefault(); // Output: first = 1, firstOrDefault = 1 |
5.2. Last and LastOrDefault
The Last method returns the last element of a sequence that satisfies a specified condition, while LastOrDefault returns the last element or a default value if the sequence is empty. Example:
1 2 3 4 5 6 7 |
int[] numbers = { 1, 2, 3, 4, 5 }; var last = numbers.Last(); var lastOrDefault = numbers.LastOrDefault(); // Output: last = 5, lastOrDefault = 5 |
5.3. Single and SingleOrDefault
The Single method returns the only element of a sequence that satisfies a specified condition, while SingleOrDefault returns the single element or a default value if the sequence is empty or contains more than one element. Example:
1 2 3 4 5 6 7 |
int[] numbers = { 1 }; var single = numbers.Single(); var singleOrDefault = numbers.SingleOrDefault(); // Output: single = 1, singleOrDefault = 1 |
5.4. ElementAt and ElementAtOrDefault
The ElementAt method returns the element at a specified index in a sequence, while ElementAtOrDefault returns the element at the specified index or a default value if the index is out of range. Example:
1 2 3 4 5 6 7 |
int[] numbers = { 1, 2, 3, 4, 5 }; var elementAt = numbers.ElementAt(2); var elementAtOrDefault = numbers.ElementAtOrDefault(10); // Output: elementAt = 3, elementAtOrDefault = 0 (default value for int) |
Section 6: Skipping and Taking Elements
6.1. Skip and SkipWhile
The Skip method skips a specified number of elements in a sequence and returns the remaining elements, while SkipWhile skips elements until a specified condition is no longer satisfied. Example:
1 2 3 4 5 6 7 |
int[] numbers = { 1, 2, 3, 4, 5 }; var skippedNumbers = numbers.Skip(2); var skippedWhileNumbers = numbers.SkipWhile(n => n < 4); // Output: skippedNumbers = 3, 4, 5, skippedWhileNumbers = 4, 5 |
6.2. Take and TakeWhile
The Take method returns a specified number of elements from the start of a sequence, while TakeWhile returns elements until a specified condition is no longer satisfied. Example:
1 2 3 4 5 6 7 |
int[] numbers = { 1, 2, 3, 4, 5 }; var takenNumbers = numbers.Take(3); var takenWhileNumbers = numbers.TakeWhile(n => n < 4); // Output: takenNumbers = 1, 2, 3, takenWhileNumbers = 1, 2, 3 |
Section 7: Joining and Grouping Data
7.1. Join
The Join method performs an inner join between two sequences based on a common key. Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
var employees = new[] { new { Id = 1, Name = "Alice", DepartmentId = 1 }, new { Id = 2, Name = "Bob", DepartmentId = 2 } }; var departments = new[] { new { Id = 1, Name = "HR" }, new { Id = 2, Name = "Finance" } }; var joinedData = employees.Join( departments, emp => emp.DepartmentId, dept => dept.Id, (emp, dept) => new { emp.Name, dept.Name } ); // Output: { Name = "Alice", Name = "HR" }, { Name = "Bob", Name = "Finance" } |
7.2. GroupBy
The GroupBy method groups elements in a sequence based on a key and returns a sequence of groups. Example:
1 2 3 4 5 6 |
string[] fruits = { "apple", "banana", "cherry", "date" }; var groupedFruits = fruits.GroupBy(fruit => fruit.Length); // Output: Group 5: "apple", "cherry", Group 6: "banana", Group 4: "date" |
LINQ extension methods in C# provide a powerful and expressive way to query and manipulate data from various sources. By utilizing these methods, you can write concise and readable code to filter, transform, sort, aggregate, retrieve, and join data effortlessly. Understanding the usage of LINQ extension methods will significantly enhance your productivity as a C# developer and simplify complex data operations in your applications.
Leave a Comment