Select
The Select method in LINQ projects each element of a sequence into a new form. It is used to transform elements in a collection.
Example
public void SelectMethod()
{
var numbers = new List<int> { 1, 2, 3, 4, 5 };
var squares = numbers.Select(x => x * x);
foreach (var square in squares)
{
Console.WriteLine(square);
}
}
In this example, Select takes each number in the list, squares it, and returns a new collection of squared numbers.
SelectMany
The SelectMany method projects each element of a sequence to an IEnumerable<T> and flattens the resulting sequences into one sequence. It is useful when working with collections of collections
public void SelectManyMethod()
{
var lists = new List<List<int>>
{
new List<int>{1,2,3},
new List<int>{4,5,6},
new List<int>{7,8,9}
};
var flatList = lists.SelectMany(x => x);
foreach (var list in flatList)
{
Console.WriteLine(list);
}
}
Output