是使用嵌套循环,合并LINQ加入经营者或HashSet的加入?嵌套、经营者、LINQ、HashSet

2023-09-03 16:35:38 作者:奈何情深

有谁知道加入算法研究做LINQ执行其加入运营商。

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

难道NestedLoop,合并,或HashSet的?有没有什么办法可以指定一个不同的,如果支持的话?

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

问候 阿尔伯特

推荐答案

首先,它有效地从内部的序列通过外序列创建查找,然后遍历。然后,它可以查找从外序列中的每个键和产量每一个合适的配对。像这样的东西(忽略参数验证等):

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.