Csharp/C#教程:连接多个IEnumerable分享


连接多个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) 

注意额外的[]

上述就是C#学习教程:连接多个IEnumerable分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1013130.html

(0)
上一篇 2021年12月30日
下一篇 2021年12月30日

精彩推荐