带有for的 LINQJoin()
方法跳过空键匹配。我在文档中遗漏了什么?我知道我可以切换到,我只是好奇为什么这个相等操作像 SQL 而不是像 C# 那样工作,因为据我所知,它的工作方式与我对空值的期望完全一样。Nullable<int>
TKey
SelectMany()
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;
}
}