Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate multiple IEnumerable<T>

Tags:

I'm trying to implement a method to concatenate multiple Lists e.g.

List<string> l1 = new List<string> { "1", "2" }; List<string> l2 = new List<string> { "1", "2" }; List<string> l3 = new List<string> { "1", "2" }; var result = Concatenate(l1, l2, l3); 

but my method doesn't work:

public static IEnumerable<T> Concatenate<T>(params IEnumerable<T> List) {     var temp = List.First();     for (int i = 1; i < List.Count(); i++)     {         temp = Enumerable.Concat(temp, List.ElementAt(i));     }     return temp; } 
like image 257
fubo Avatar asked Nov 21 '14 08:11

fubo


1 Answers

Use SelectMany:

public static IEnumerable<T> Concatenate<T>(params IEnumerable<T>[] lists) {     return lists.SelectMany(x => x); } 
like image 111
brz Avatar answered Oct 13 '22 07:10

brz