Is LINQ Join operator using Nested Loop, Merge, or HashSet Joins?

China☆狼群 提交于 2019-12-07 02:55:02

问题


Does anyone know what Join algorith does LINQ performs with its Join operator.

Is it NestedLoop, Merge, or HashSet? Is there any way to specify a different one, if supported?

Regards Albert


回答1:


First it effectively creates a lookup from the "inner" sequence, then iterates through the outer sequence. It can then look up each key from the outer sequence and yield each appropriate pair. Something like this (ignoring argument validation etc):

public static IEnumerable<TResult> Join<TOuter, TInner, TKey, TResult>
    (this IEnumerable<TOuter> outer,
     IEnumerable<TInner> inner,
     Func<TOuter, TKey> outerKeySelector,
     Func<TInner, TKey> innerKeySelector,
     Func<TOuter, TInner, TResult> resultSelector)
{
    Lookup<TKey, TInner> lookup = inner.ToLookup(innerKeySelector);
    foreach (TOuter outerItem in outer)
    {
        TKey key = outerKeySelector(outerItem);
        foreach (TInner innerItem in lookup[key])
        {
            yield return resultSelector(outerItem, innerItem);
        }
    }
}

The lookup will use a hash table internally for the keys, so that it's efficient to look up any individual key.



来源:https://stackoverflow.com/questions/1561622/is-linq-join-operator-using-nested-loop-merge-or-hashset-joins

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!