Concatenate multiple IEnumerable

前端 未结 4 1389
鱼传尺愫
鱼传尺愫 2021-01-07 18:11

I\'m trying to implement a method to concatenate multiple Lists e.g.

List l1 = new List { \"1\", \"2\" };
List

        
相关标签:
4条回答
  • 2021-01-07 19:00

    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;
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-07 19:00

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

    0 讨论(0)
  • 2021-01-07 19:04

    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;
    }
    
    0 讨论(0)
  • Use SelectMany:

    public static IEnumerable<T> Concatenate<T>(params IEnumerable<T>[] lists)
    {
        return lists.SelectMany(x => x);
    }
    
    0 讨论(0)
提交回复
热议问题