Tuesday, February 25, 2014

C# - LINQ - Flatten nested Lists

Enumerable.SelectMany<TSource, TResult> Method (IEnumerable<TSource>, Func<TSource, IEnumerable<TResult>>)

Projects each element of a sequence to an IEnumerable and flattens the resulting sequences into one sequence.

IEnumerable group = new List(); // Select gets a list of lists of phone numbers IEnumerable> phoneLists = group.Select(g => g.Phones); // SelectMany flattens nested lists of phone numbers to a single list List phoneNumbers = group.SelectMany(g => g.Phones).ToList(); public class Phone { public string Number { get; set; } } public class Member { public IEnumerable Phones { get; set; } }

Share/Bookmark

No comments: