多个IEnumerable<T>连接(concatenate)

30

我正在尝试实现一个方法来连接多个List,例如:

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

但是我的方法不起作用:

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

3
在每个循环中调用IEnumerable.Count()有点浪费。调用一次并将其存储在变量中,或者更好的方法是使用foreach循环:var Temp = List.First(); foreach (IEnumerable<T> sequence in List.Skip(1)) Temp = Enumerable.Concat(sequence); - Pieter Witvoet
4个回答

92

使用 SelectMany

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

8

仅为完整起见,另一种值得注意的方法是:

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

如果您想使函数起作用,需要一个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;
}

3
参数 List 是一个包含多个 IEnumerable 的数组,它可能没有任何项。这会导致 List.First() 抛出异常。你应该先检查这个数组的长度。在 for 循环中,我将使用 Length 属性和索引器 List[] 而不是等效的 Linq 扩展。 - Luca Cremonesi
3
不要使用常见的类名作为变量名。 =( - jpmc26

-2

你所需要做的就是改变:

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

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

请注意额外的[]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接