2

In the given code example, why do we use x.ToArray() ? Each element x is already an array isn't it ?

Please make me less confused :)

    var array1 = new int[3] { 1, 2, 3 };     //New integer array
    var array2 = new int[3] { 4, 5, 6 };     //New integer array
    var array3 = new int[3] { 7, 8, 9 };     //New integer array

    IList<int[]> list4 = new List<int[]> { array1, array2, array3 };

    var theManyList = list4.SelectMany(x => x.ToArray()).ToList();
HerbalMart
  • 1,669
  • 3
  • 27
  • 50
  • 1
    Also see this question http://stackoverflow.com/questions/958949/difference-between-select-and-selectmany – Mike Two Aug 04 '12 at 19:03

1 Answers1

6

You don't need it. You can just do:

list4.SelectMany(x => x).ToList();

The reason is exactly as you stated it, the arrays are already arrays. SelectMany takes an IEnumerable<T>, so no need to add the extra operation. Why someone did that in an example, don't know. Maybe they were trying to make it clear that you had to pass an IEnumerable?

pstrjds
  • 16,840
  • 6
  • 52
  • 61
  • 1
    is right. SelectMany consumes `IEnumerable` so it makes no sense making an array out of x - even if it is not an array, but just an 'IEnumerable'. **However** sometimes `.ToArray()` is used inside Linq statements to prevent deffered execution. – George Mamaladze Jul 24 '12 at 17:12
  • @achitaka-san - Good call on the preventing deferred execution, I hadn't thought of that case. Most of the time when I am doing any LINQ I want the deferred execution. – pstrjds Jul 24 '12 at 17:21