Select vs SelectMany


In LINQ, Select and SelectMany are used to project and flatten sequences of data, but they work differently.

1. Select

  • Purpose - Projects each element of a sequence into a new form.
  • Output - Returns a sequence where each element is transformed according to a specified projection function.
  • Use Case - When you want to transform each item in a collection into another type or shape.

Example

var numbers = new List<int> { 1, 2, 3 };
var squaredNumbers = numbers.Select(n => n * n);
// squaredNumbers: { 1, 4, 9 }

2. SelectMany

  • Purpose - Projects each element of a sequence to an IEnumerable<T> and flattens the resulting sequences into one sequence.
  • Output - Returns a single sequence that is the result of concatenating all the sequences produced by the projection function.
  • Use Case - When each element in the collection is itself a collection, and you want to flatten the result into a single collection.

Example

var numbers = new List<int> {
    new List { 1, 2 },
    new List { 3, 4 }
};
var flattened = numbers.SelectMany(n => n);
// flattened: { 1, 2, 3, 4 }

Key Differences

  • Select maintains the structure of the original collection, whereas SelectMany flattens the structure.
  • Use Select when projecting to a different type or shape, and use SelectMany when you need to flatten nested collections.

Prev Next