这是一个对首先从代码中提取的 linq 路径进行赋值的示例...
applicants = appRegistrations
.ToList()
.Select(c => new ApplicantList() {
PartnerType = c.Participant != null ? c.Participant.PartnerType != null ? c.Participant.PartnerType.PartnerTypeName : "" : ""
});
注意 null 检查 - 考虑到 Participant AND PartnerType 可能为 null,是否有更优雅的方式可以编写此代码?
我只是讨厌检查每个属性上的空值。
最佳答案
您可以检查两者之一是否为null
:
List<ApplicantList> applicants = appRegistrations
.Select(ar => c.Participant == null || c.Participant.PartnerType == null
? "" : c.Participant.PartnerType.PartnerTypeName)
.Select(str => new ApplicantList { PartnerType = str })
.ToList();
关于c# - 检查 Linq 路径中空值的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21368532/