29

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;
}
g t
  • 7,287
  • 7
  • 50
  • 85
fubo
  • 44,811
  • 17
  • 103
  • 137
  • 3
    Calling IEnumerable.Count() every cycle is a bit of a waste. Call it once and store it in a variable, or better, use a foreach loop: `var Temp = List.First(); foreach (IEnumerable sequence in List.Skip(1)) Temp = Enumerable.Concat(sequence);`. – Pieter Witvoet Nov 21 '14 at 08:51

4 Answers4

90

Use SelectMany:

public static IEnumerable<T> Concatenate<T>(params IEnumerable<T>[] lists)
{
    return lists.SelectMany(x => x);
}
brz
  • 5,926
  • 1
  • 18
  • 18
8

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;
        }
    }
}
fubo
  • 44,811
  • 17
  • 103
  • 137
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;
}
Fabian S.
  • 909
  • 6
  • 20
  • 3
    The parameter `List` is an array of IEnumerables and it could contain no items. This will cause `List.First()` to throw an exception. You should first check the length of this array. I will also use the `Length` property and the indexer `List[]` instead of the equivalent Linq extensions in the for loop. – Luca Cremonesi Feb 22 '16 at 16:51
  • 3
    Don't use a common class name as a variable name. =( – jpmc26 Jul 08 '17 at 00:35
-2

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 [].

vsarunov
  • 1,433
  • 14
  • 26
SmartDev
  • 2,802
  • 1
  • 17
  • 22