Wednesday, January 18, 2017

How to flatten a list of lists into a flat list in one line of code: SelectMany is your friend

Given that you have a list of lists, how do you flatten it?

how do you flatten it?

With the SelectMany LINQ method, it's easy peasy:

var listOfLists = new List<IEnumerable<int>>() { Enumerable.Range(1, 3), Enumerable.Range(20, 3) };
listOfLists.Dump("List of lists");
listOfLists.SelectMany(lol => lol).Dump("Flat list");

Download linqpad sample, here

No comments: