Select()
- Purpose: Projects each element in a sequence into a new form.
- Returns: A Sequence (IEnumerable) where each element is transformed.
- Use case: Modify each element in a collection.
Example:
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
// Square each number
var squaredNumbers = numbers.Select(n => n * n).ToList();
Console.WriteLine("Squared Numbers: " + string.Join(", ", squaredNumbers));
// Output: Squared Numbers: 1, 4, 9, 16, 25
}
}
SelectMany()
- Purpose: Flattens nested collections into a single sequence.
- Returns: A single IEnumerable<T> instead of nested lists.
- Use case: Useful when each item in a collection is a single item, and we need a flat structure.
Example:
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<List<int>> numberGroups = new List<List<int>>
{
new List<int> { 1, 2, 3 },
new List<int> { 4, 5 },
new List<int> { 6, 7, 8, 9 }
};
// Flatten the lists
var flattenedNumbers = numberGroups.SelectMany(group => group).ToList();
Console.WriteLine("Flattened Numbers: " + string.Join(", ", flattenedNumbers));
// Output: Flattened Numbers: 1, 2, 3, 4, 5, 6, 7, 8, 9
}
}
Differences:
- Select() maintains the nested structure
- SelectMany() flattens the collection
Zip()
- Purpose: Merges two collections in pairs into a new sequence.
- Returns: A sequence where the elements of both collections are combined.
- Use case: Useful for parallel processing of two lists.
Example: Merging two Lists
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
List<int> scores = new List<int> { 85, 92, 78 };
// Merge names and scores
var studentScores = names.Zip(scores, (name, score) => $"{name}: {score}").ToList();
Console.WriteLine("Student Scores: " + string.Join(", ", studentScores));
// Output: Student Scores: Alice: 85, Bob: 92, Charlie: 78
}
}
Key Points about Zip()
- This works only if both lists have the same length.
- If one list is shorter, the extra elements of the longer list are ignored.
Also, Read: LINQ where() and OfType() using C#.
Leave Comment