Linq with safe cast and zero check

Based on 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 casting safely (i as EmployeeDto) I can get a NullReferenceException. How can I ensure and ensure the security of the code, and not overload it with a lot of null checks?

Solution Overview:

I did some tests to confirm whether the solutions worked. Both work well and bring the same result, you can check HERE . After that I did some performance tests with OfTypeSolution and letSolution .

As OfType's solution has the best times on average, it will be the answer!

+4
source share
2 answers

You can use OfType before 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 with only those elements of type EmployeeDto from SelectedItems , so there is no need to check and check null.

+8
source
 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 } 
+2
source

Source: https://habr.com/ru/post/1435083/


All Articles