C# Lambda returns some null values

2019-04-22 20:09发布

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?

5条回答
看我几分像从前
2楼-- · 2019-04-22 20:49

Try getting the problem code first, then check if it's null.

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

openCall.Priority = 
    possiblyNullProblemCode == null ? 
        string.Empty : 
        possiblyNullProblemCode.Priority;
查看更多
聊天终结者
3楼-- · 2019-04-22 20:56

You can simply write:

opencall.Priority = 
    averages.Where(x => x.ProblemCode == opencall.ProblemCode)
    .Select(x => x.Priority)
    .SingleOrDefault() ?? string.Empty;
查看更多
Lonely孤独者°
4楼-- · 2019-04-22 20:57

Assuming Priority is string, you could try:

var average = averages.Where(x => x.ProblemCode == opencall.ProblemCode).SingleOrDefault()
opencall.Priority = average == null ? "" : average.Priority;
查看更多
Animai°情兽
5楼-- · 2019-04-22 21:07

Split it up:

 var result = averages.Where(x => x.ProblemCode == opencall.ProblemCode).SingleOrDefault()
 opencall.Priority = result != null ? result.Priority : string.Empty;
查看更多
Lonely孤独者°
6楼-- · 2019-04-22 21:12

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.

查看更多
登录 后发表回答