c# - 具有安全转换和空验证的 Linq

标签 c# linq nullreferenceexception

给定代码:

from i in this.GridViewFoo.SelectedItems
select new EmployeeEntity
{
    EmployeeID = (i as EmployeeDto).EmployeeID,
    Email = this.GetAllEmail((i as EmployeeDto).Email, (i as EmployeeDto).SecondaryEmails),
    EmployeeNumber = (i as EmployeeDto).EmployeeNumber,
    FirstName = (i as EmployeeDto).FirstName,
    LastName = (i as EmployeeDto).LastName
}

安全转换后 (i as EmployeeDto) 我可能会收到 NullReferenceException。我如何确保代码的安全性,而不是让他因大量空检查而重载?

解决方案概述:

我做了一些测试来断言这些解决方案是否有效。两者都运行良好并带来相同的结果,您可以查看 HERE .之后我用 OfTypeSolution 做了一些性能测试和 letSolution .

由于 OfType 解决方案的平均时间更好,这就是答案!

最佳答案

您可以使用 OfTypeSelect 之前:

from i in this.GridViewFoo.SelectedItems.OfType<EmployeeDto>()
select new EmployeeEntity
{
    EmployeeID = i.EmployeeID,
    Email = this.GetAllEmail(i.Email, i.SecondaryEmails),
    EmployeeNumber = i.EmployeeNumber,
    FirstName = i.FirstName,
    LastName = i.LastName
}

它只会为您提供 SelectedItems 中的 EmployeeDto 类型的项目,因此无需强制转换和空值检查。

关于c# - 具有安全转换和空验证的 Linq,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12497693/

相关文章:

c# - CS0176编译器错误。这是什么意思,我该如何解决

vuejs2 - 类星体 2 Vue 3 "ReferenceError: process is not defined"错误

c# - ApplicationBarIconButton 名称引用会导致 NullReferenceException,但并非在所有 Windows Phone 7 应用程序中?

c# - 在 C# 中重载运算符 =。我怎样才能接受其他类型?

c# - 降级到 .net 3.5 后找不到 Linq

c# - 使用 Linq 返回节点中的属性列表

c# - 什么是NullReferenceException,如何解决?

c# - 如何在 C# 中的 SSH 服务器上运行命令?

c# - 暂时关闭 WPF 中的绑定(bind)

c# - 使用 分配委托(delegate)时出错? : Syntax