Thursday, November 3, 2022

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

Issue

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?


Solution

Use the SelectMany extension method

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


Answered By - JaredPar
Answer Checked By - Katrina (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.