How does Concat () actually join collections at a lower level?

What does Linq really do?

+3
source share
3 answers

(I assume this is for LINQ for objects. Everything else will be implemented differently :)

It simply returns everything from the first, and then everything from the second. All data is streamed. Something like that:

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

I divided this into two methods to verify the argument is correct, but I can still use an iterator block. (No code inside the iterator block is executed until the first call of the MoveNext()result).

+9
source

It lists each collection in turn and gives each item. Something like that:

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

+1

It depends on the LINQ provider you are using. LinqToSql or L2E can use UNION databases, while LINQ to Objects can just list both collections for you in turn.

+1
source

Source: https://habr.com/ru/post/1745306/


All Articles