C# 当equals左侧的类可以为null时,Linq left join
考虑以下情况: 课程C# 当equals左侧的类可以为null时,Linq left join,c#,linq,left-join,C#,Linq,Left Join,考虑以下情况: 课程 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 {g
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};
实例
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};
当p.NestedType
为空时,查询将在equals
语句行引发异常
我想要实现的是:当p.NestedType
为null时,应该放置一个null
值,而不是它;就好像分配了p.NestedType
,但其Id
为空。能做到吗
编辑:我必须使用C#5.0 使用where(…)
子句,您可以防止在您的案例中引发空引用异常,并检查这是否为您的案例生成所需的结果:
var query = from p in pairs
where p.NestedType!=null //Notice the where condition added
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
};
或
如果希望始终获取所有左侧值,例如,在您的情况下,如果结果应如下所示,则可以使用:
或
如果我们需要在C#5中执行此操作,如下面所述,您可以执行以下操作:
var query = from p in pairs
let nestedTypeId = (p != null && p.NestedType != null) ? p.NestedType.Id : null
join m in matches on nestedTypeId 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
为空的整行。实际上,我希望该行出现—毕竟它是一个左连接。我必须使用C#5。0@HeyJudeC#5的最新答案。希望能对您有所帮助。这正是p?上的-的目的。NestedType.Id等于m.Id