Search code examples
c#linq

Different ways of using SelectMany()


I'd like to know how to use SelectMany(). It seems to take so many arguments and from my own research I noticed that SelectMany() might be the 'father' of all other select operations.


Solution

  • Select many allows you to select a property from your query source that is an IEnumerable<T> collection, but instead of returning a collection of collections (IEnumerable<IEnumerable<T>>) it will flatten the collections into a single collection.

    Here's an example that you can run to demonstrate the differences between Select and SelectMany:

    //set up some data for our example
    var tuple1 = new { Name = "Tuple1", Values = new int [] { 1, 2, 3 } };
    var tuple2 = new { Name = "Tuple2", Values = new int [] { 4, 5, 6 } };
    var tuple3 = new { Name = "Tuple3", Values = new int [] { 7, 8, 9 } };
    
    //put the tuples into a collection
    var tuples = new [] { tuple1, tuple2, tuple3 };
    
    //"tupleValues" is an IEnumerable<IEnumerable<int>> that contains { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }
    var tupleValues = tuples.Select(t => t.Values);
    
    //"tupleSelectManyValues" is an IEnumerable<int> that contains { 1, 2, 3, 4, 5, 6, 7, 8, 9 }
    var tupleSelectManyValues = tuples.SelectMany(t => t.Values);
    

    By using SelectMany you make it easier to query values within child collections.