【问题标题】:Linq with safe cast and null verification具有安全强制转换和空值验证的 Linq
【发布时间】:2012-09-19 15:16:50
【问题描述】:

给定代码:

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。我怎样才能确保代码的安全性,又不会因为大量的 null 检查而使他超负荷?

解决方案概述:

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

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

【问题讨论】:

标签: c# linq nullreferenceexception


【解决方案1】:

你可以在Select之前使用OfType

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
}

它只会为您提供来自 SelectedItemsEmployeeDto 类型项目,因此无需强制转换和空值检查。

【讨论】:

  • 这也避免了输出中出现大量空条目。
【解决方案2】:
from si in this.GridViewFoo.SelectedItems
let i = si as EmployeeDto
where i != null
select new EmployeeEntity
{
    EmployeeID = i.EmployeeID,
    Email = this.GetAllEmail(i.Email, i.SecondaryEmails),
    EmployeeNumber = i.EmployeeNumber,
    FirstName = i.FirstName,
    LastName = i.LastName
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    • 2018-06-12
    • 2015-05-25
    • 2012-05-12
    相关资源
    最近更新 更多