How to merge a list of lists with same type of items to a single list of items?

David.Chu.ca picture David.Chu.ca · Jul 28, 2009 · Viewed 99.9k times · Source

The question is confusing, but it is much more clear as described in the following codes:

   List<List<T>> listOfList;
   // add three lists of List<T> to listOfList, for example
   /* listOfList = new {
        { 1, 2, 3}, // list 1 of 1, 3, and 3
        { 4, 5, 6}, // list 2
        { 7, 8, 9}  // list 3
        };
   */
   List<T> list = null;
   // how to merger all the items in listOfList to list?
   // { 1, 2, 3, 4, 5, 6, 7, 8, 9 } // one list
   // list = ???

Not sure if it possible by using C# LINQ or Lambda?

Essentially, how can I concatenate or "flatten" a list of lists?

Answer

JaredPar picture JaredPar · Jul 28, 2009

Use the SelectMany extension method

list = listOfList.SelectMany(x => x).ToList();