考虑以下情况:LINQ的左连接时,在等号的左边的类可以是空
类
public class Nested
{
public Nested(int id){ Id = id; }
public int? Id {get; set;}
}
public class Pair
{
public Nested NestedType {get; set;}
public string Name {get; set;}
}
public class Match
{
public int? Id {get; set;}
public string Name {get; set;}
}
实例
var p1 = new Pair();
p1.NestedType = new Nested(1);
p1.Name = "a";
var p2 = new Pair();
p2.NestedType = null;
p2.Name = "b";
var p3 = new Pair();
p3.NestedType = new Nested(3);
p3.Name = "c";
List<Pair> pairs = new List<Pair>() {p1, p2, p3};
var m1 = new Match();
m1.Id = 1;
m1.Name = "AA";
var m2 = new Match();
m2.Id = null;
m2.Name = "BB";
var m3 = new Match();
m3.Id = 3;
m3.Name = "CC";
List<Match> matches = new List<Match>(){m1, m2, m3};
查询
var query = from p in pairs
join m in matches on p.NestedType.Id equals m.Id into pm
from m in pm.DefaultIfEmpty()
select new
{
PairName = p.Name,
MatchId = m != null ? m.Id : null
MatchName = m != null ? m.Name : null
};
当p.NestedType
为空时,查询将在equals
语句行上抛出异常。
我想达到的是:当p.NestedType
为空时,应该放置一个null
值而不是它;这好像是p.NestedType
已分配,但其Id
为空。可以做到吗?编辑:我不得不使用C#5.0。
这正是[C#空条件操作符(HTTPS ://msdn.microsoft.com/en-us/library/dn986595.aspx)用于 - 'on p?.NestedType.Id等于m.Id' –