LINQ加入Nullable密钥

rya*_*ium 5 c# linq

用于跳过null键匹配的LINQ Join()方法.我在文档中遗漏了什么?我知道我可以切换到,我只是好奇为什么这个相等的操作像SQL一样工作而不像C#,因为尽可能接近我所能说的,这些工作与我期望它的null值完全相同.Nullable<int>TKeySelectMany()EqualityComparer<int?>.Default

http://msdn.microsoft.com/en-us/library/bb534675.aspx

using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;

public class dt
{
   public int? Id;
   public string Data;
}

public class JoinTest
{
    public static int Main(string [] args)
    {
        var a = new List<dt>
        {
            new dt { Id = null, Data = "null" },
            new dt { Id = 1, Data = "1" },
            new dt { Id = 2, Data = "2" }
        };

        var b = new List<dt>
        {
            new dt { Id = null, Data = "NULL" },
            new dt { Id = 2, Data = "two" },
            new dt { Id = 3, Data = "three" }
        };

        //Join with null elements
        var c = a.Join( b,
            dtA => dtA.Id,
            dtB => dtB.Id,
            (dtA, dtB) => new { aData = dtA.Data, bData = dtB.Data } ).ToList();
        // Output:
        // 2 two
        foreach ( var aC in c )
            Console.WriteLine( aC.aData + " " + aC.bData );
        Console.WriteLine( " " );

        //Join with null elements converted to zero
        c = a.Join( b,
            dtA => dtA.Id.GetValueOrDefault(),
            dtB => dtB.Id.GetValueOrDefault(),
            (dtA, dtB) => new { aData = dtA.Data, bData = dtB.Data } ).ToList();

        // Output:
        // null NULL
        // 2 two
        foreach ( var aC in c )
            Console.WriteLine( aC.aData + " " + aC.bData );

        Console.WriteLine( EqualityComparer<int?>.Default.Equals( a[0].Id, b[0].Id ) );
        Console.WriteLine( EqualityComparer<object>.Default.Equals( a[0].Id, b[0].Id ) );
        Console.WriteLine( a[0].Id.Equals( b[0].Id ) );

        return 0;
    }
}
Run Code Online (Sandbox Code Playgroud)

Ser*_*kiy 5

Enumerable.Join使用JoinIterator(私有类)迭代匹配的元素。JoinIterator使用Lookup<TKey, TElement>创建序列键查找:

internal static Lookup<TKey, TElement> CreateForJoin(
    IEnumerable<TElement> source, 
    Func<TElement, TKey> keySelector, 
    IEqualityComparer<TKey> comparer)
{
    Lookup<TKey, TElement> lookup = new Lookup<TKey, TElement>(comparer);
    foreach (TElement local in source)
    {
        TKey key = keySelector(local);
        if (key != null) // <--- Here
        {
            lookup.GetGrouping(key, true).Add(local);
        }
    }
    return lookup;
}
Run Code Online (Sandbox Code Playgroud)

有趣的部分是跳过键null。因此,如果不提供默认值,则只有一个匹配项。


看来我找到了这种行为的原因。查找使用默认的EqualityComparer,它将0为key null和两者返回0

int? keyA = 0;
var comparer = EqualityComparer<int?>.Default;
int hashA = comparer.GetHashCode(keyA) & 0x7fffffff; // from Lookup class
int? keyB = null;
int hashB = comparer.GetHashCode(keyB) & 0x7fffffff;
Console.WriteLine(hashA); // 0
Console.WriteLine(hashB); // 0
Run Code Online (Sandbox Code Playgroud)

可能会跳过null以避免匹配null0键。