.net - 第一或默认 : Default value other than null

标签 .net linq

据我了解,在 Linq 中,方法 FirstOrDefault() 可以返回 null 以外的 Default 值。我还没有弄清楚的是,当查询结果中没有项目时,这个(和类似的)方法可以返回除 null 之外的什么类型的东西。是否有任何特定的方法可以设置它,以便如果特定查询没有值,则返回一些预定义值作为默​​认值?

最佳答案

As I understand it, in Linq the method FirstOrDefault() can return a Default value of something other than null.

没有。或者更确切地说,它总是返回元素类型的默认值...它可以是 null 引用、可为 null 值类型的 null 值,也可以是非元素的自然“全零”值。 -可为空的值类型。

Is there any particular way that this can be set up so that if there is no value for a particular query some predefined value is returned as the default value?

对于引用类型,您可以使用:

var result = query.FirstOrDefault() ?? otherDefaultValue;

当然,如果第一个值存在,但它是一个空引用,这也会为您提供“其他默认值”...

关于.net - 第一或默认 : Default value other than null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12972295/

相关文章:

c# - 为什么我的表在 ASP.NET 中没有内容?

c# - C# .NET Singleton 类中的静态方法是否会对性能或内存消耗产生负面影响?

asp.net - 如何更改 asp Updatepanel 的标准事件处理程序签名?

c# - 如何在 C# 中使用 LINQ 查找乱序元素

c# - 假设注册表配置单元始终相同有多安全?

.net - 如果我正在引导我的安装,我是否必须显示 .NET EULA

c# - 如何在单个 Linq 表达式中混合 monadic 构造?

c# - 无法将类型 'System.Linq.IQueryable<double?>' 转换为 'float'

c# - 当父节点等于 LINQ to XML 中的特定值时如何选择子节点

c# - 在 MatchCollection 上使用 LINQ 扩展方法语法