Linq具有安全转换和空验证

时间:2012-09-19 15:16:51

标签: 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。之后,我使用OfTypeSolutionletSolution进行了一些性能测试。

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

2 个答案:

答案 0 :(得分:8)

您可以在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
}

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

答案 1 :(得分: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
}