c# - 检查 Linq 路径中空值的更好方法

标签 c# asp.net linq

这是一个对首先从代码中提取的 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/

相关文章:

c# - Winforms - 当任何表单加载到设计器中时执行函数

c# - 使用 AutoMapper 进行转换

c# - 每次页面加载时都会触发按钮的 OnClick 事件

c# - 正则表达式提取多个句子,同时丢弃特定句子

javascript - 从 asp.net 中的代码隐藏文件获取 json 到 javascript

c# - 即使我调用 CloudBlob.SetMetadata,Blob 元数据也不会保存

performance - 链接 LINQ 语句是否会导致多次迭代?

mysql - 使用linq编写sql语句

c# - SelectMany 时最小起订量验证失败

c# - 错误 : The type 'System.Data.OleDb.OleDbDataReader' has no constructors defined