fub*_*ubo 19 c# ienumerable concatenation
我正在尝试实现一个连接多个Lists 的方法
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);
Run Code Online (Sandbox Code Playgroud)
但我的方法不起作用:
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;
}
Run Code Online (Sandbox Code Playgroud)
brz*_*brz 64
用途SelectMany:
public static IEnumerable<T> Concatenate<T>(params IEnumerable<T>[] lists)
{
return lists.SelectMany(x => x);
}
Run Code Online (Sandbox Code Playgroud)
为了完整起见,另一种值得注意的方法:
public static IEnumerable<T> Concatenate<T>(params IEnumerable<T>[] List)
{
foreach (IEnumerable<T> element in List)
{
foreach (T subelement in element)
{
yield return subelement;
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10561 次 |
| 最近记录: |