连接多个IEnumerable
我正在尝试实现一个连接多个List
的方法,例如
List l1 = new List { "1", "2" }; List l2 = new List { "1", "2" }; List l3 = new List { "1", "2" }; var result = Concatenate(l1, l2, l3);
但我的方法不起作用:
public static IEnumerable Concatenate(params IEnumerable List) { var temp = List.First(); for (int i = 1; i < List.Count(); i++) { temp = Enumerable.Concat(temp, List.ElementAt(i)); } return temp; }
使用SelectMany
:
public static IEnumerable Concatenate (params IEnumerable [] lists) { return lists.SelectMany(x => x); }
如果你想让你的函数工作,你需要一个IEnumerable数组:
public static IEnumerable Concartenate (params IEnumerable [] List) { var Temp = List.First(); for (int i = 1; i < List.Count(); i++) { Temp = Enumerable.Concat(Temp, List.ElementAt(i)); } return Temp; }
只是为了完整性另一个值得注意的方法:
public static IEnumerable Concatenate (params IEnumerable [] List) { foreach (IEnumerable element in List) { foreach (T subelement in element) { yield return subelement; } } }
你所要做的就是改变:
public static IEnumerable Concartenate (params IEnumerable List)
至
public static IEnumerable Concartenate (params [] List)
注意额外的[]
。