Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Lambda returns some null values

Tags:

c#

.net

lambda

linq

opencall.Priority = 
averages.Where(x => x.ProblemCode == opencall.ProblemCode)
.SingleOrDefault().Priority;

The above lambda statement returns some nulls because ProblemCode isn't always guaranteed to be in the averages list.

How can I rewrite this statement so that if that is the case opencall.Priority is set to "" instead of the application throwing an error?

like image 350
markp3rry Avatar asked Feb 06 '13 15:02

markp3rry


2 Answers

You have to provide a new default value for your reference type, other than null.

opencall.Priority = averages.Where(x => x.ProblemCode == opencall.ProblemCode)
                            .Select(x => x.Priority)
                            .DefaultIfEmpty("")
                            .Single(); 

So Priority is a string? Note that you don't need SingleOrDefault anymore since the query can never throw an exception because it is empty when you provide a DefaultIfEmpty.

like image 95
Tim Schmelter Avatar answered Sep 21 '22 19:09

Tim Schmelter


Split it up:

 var result = averages.Where(x => x.ProblemCode == opencall.ProblemCode).SingleOrDefault()
 opencall.Priority = result != null ? result.Priority : string.Empty;
like image 39
Arcturus Avatar answered Sep 21 '22 19:09

Arcturus