Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq with safe cast and null verification

Given the code:

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
}

After the safe cast (i as EmployeeDto) may I receive a NullReferenceException. How can I ensure and safety of the code and not overload him with a lot of null checks?

Overview of solutions:

I did some tests to assert if the solutions are working. Both are working well and bring the same result, you can check HERE. After that I did some performance tests with OfTypeSolution and letSolution.

As OfType solution have better times in average, this will be the answer!

like image 700
Custodio Avatar asked Dec 15 '22 19:12

Custodio


2 Answers

You can use OfType before the Select:

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
}

it will provide you only with the EmployeeDto type items from the SelectedItems so there is no need to cast and null checking.

like image 192
nemesv Avatar answered Jan 05 '23 17:01

nemesv


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
}
like image 34
Wasp Avatar answered Jan 05 '23 18:01

Wasp