代码之家  ›  专栏  ›  技术社区  ›  zsharp

concat()是如何在较低级别上加入集合的?

  •  3
  • zsharp  · 技术社区  · 15 年前

    Linq实际上在做什么?

    3 回复  |  直到 15 年前
        1
  •  9
  •   Jon Skeet    15 年前

    (我假设这是Linq to对象。其他任何事情都将以不同的方式实现:)

    它只是从一开始就返回所有东西,然后从二开始就返回所有东西。所有数据都被流化。像这样:

    public static IEnumerable<T> Concat(this IEnumerable<T> source1,
        IEnumerable<T> source2)
    {
        if (source1 == null)
        {
            throw new ArgumentNullException("source1");
        }
        if (source2 == null)
        {
            throw new ArgumentNullException("source1");
        }
        return ConcatImpl(source1, source2);
    }
    
    
    private static IEnumerable<T> ConcatImpl(this IEnumerable<T> source1,
        IEnumerable<T> source2)
    {
        foreach (T item in source1)
        {
            yield return item;
        }
        foreach (T item in source2)
        {
            yield return item;
        }
    }
    

    我已经将其分为两种方法,以便可以急切地执行参数验证,但我仍然可以使用迭代器块。(直到第一次调用 MoveNext() 关于结果。

        2
  •  1
  •   Thomas Levesque    15 年前

    它依次枚举每个集合,并生成每个元素。就像这样:

    public static IEnumerable<T> Concat<T>(this IEnumerable<T> source, IEnumerable<T> other)
    {
        foreach(var item in source) yield return item;
        foreach(var item in other) yield return item;
    }
    

    (如果使用Reflector查看实际的实现,您将看到迭代器实际上是在单独的方法中实现的)

        3
  •  1
  •   tster    15 年前

    这取决于您使用的LINQ提供程序。LinqToSQL或L2e可能使用数据库联合,而LinqToObjects可能只是依次为您枚举这两个集合。