【问题标题】:Concatenate multiple IEnumerable<T>连接多个 IEnumerable<T>
【发布时间】:2015-01-19 08:09:00
【问题描述】:

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

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

【问题讨论】:

  • 每个周期调用 IEnumerable.Count() 有点浪费。调用一次并将其存储在变量中,或者更好的是,使用 foreach 循环:var Temp = List.First(); foreach (IEnumerable&lt;T&gt; sequence in List.Skip(1)) Temp = Enumerable.Concat(sequence);

标签: c# concatenation ienumerable


【解决方案1】:

使用SelectMany:

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

【讨论】:

    【解决方案2】:

    如果你想让你的函数工作,你需要一个 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;
    }
    

    【讨论】:

    • 参数List 是一个 IEnumerables 数组,它不能包含任何项目。这将导致List.First() 抛出异常。您应该首先检查此数组的长度。我还将在 for 循环中使用 Length 属性和索引器 List[] 而不是等效的 Linq 扩展。
    • 不要使用通用类名作为变量名。 =(
    【解决方案3】:

    你所要做的就是改变:

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

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

    注意额外的[]

    【讨论】:

      【解决方案4】:

      为了完整性,另一个 imo 值得注意的方法:

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

      【讨论】:

        猜你喜欢
        • 2012-12-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多