C#的lambda返回一些空值

C#的lambda返回一些空值

本文介绍了C#的lambda返回一些空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

以上的lambda语句返回空值的一些问题,因为code并不总是保证在平均值列表中。

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

我怎么能改写这个声明,这样,如果是这样的话opencall.Priority设置为,而不是应用程序抛出一个错误?

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?

推荐答案

您必须提供一个新的默认值,以供大家参考型,不是

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();

所以优先级字符串?请注意,您不需要的SingleOrDefault 了,因为查询不能抛出一个异常,因为当你提供给它是空的一个 DefaultIfEmpty

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.

这篇关于C#的lambda返回一些空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 15:05