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

1 comment:

Coepd BA Trainings said...

We at Coepd declared Data Science Internship Programs (Self sponsored) for professionals who want to have hands on experience. We are providing this program in alliance with IT Companies in COEPD Hyderabad premises. This program is dedicated to our unwavering participants predominantly acknowledging and appreciating the fact that they are on the path of making a career in Data Science discipline. This internship is designed to ensure that in addition to gaining the requisite theoretical knowledge, the readers gain sufficient hands-on practice and practical know-how to master the nitty-gritty of the Data Science profession. More than a training institute, COEPD today stands differentiated as a mission to help you "Build your dream career" - COEPD way.

http://www.coepd.com/AnalyticsInternship.html