Concatenate multiple IEnumerable<T>

房东的猫 提交于 2019-11-30 01:17:20

问题


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;
}

回答1:


Use SelectMany:

public static IEnumerable<T> Concatenate<T>(params IEnumerable<T>[] lists)
{
    return lists.SelectMany(x => x);
}



回答2:


Just for completeness another imo noteworthy approach:

public static IEnumerable<T> Concatenate<T>(params IEnumerable<T>[] List)
{
    foreach (IEnumerable<T> element in List)
    {
        foreach (T subelement in element)
        {
            yield return subelement;
        }
    }
}



回答3:


If you want to make your function work you need an array of IEnumerable:

public static IEnumerable<T> Concartenate<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;
}



回答4:


All you have to do is to change:

public static IEnumerable<T> Concatenate<T>(params IEnumerable<T> lists)

to

public static IEnumerable<T> Concatenate<T>(params IEnumerable<T>[] lists)

Note the extra [].



来源:https://stackoverflow.com/questions/27056967/concatenate-multiple-ienumerablet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!