c# - IEnumerable 上的 FirstOrDefault 具有不可为空的内容

标签 c# ienumerable

我需要返回 IEnumerable 的第一个元素。如果 IEnumerable 为空,我将返回一个特殊值。

此代码可能如下所示:

return myEnumerable.FirstOrDefault() ?? mySpecialValue;

myEnumerable 包含可为 null 的内容之前,这很好并且工作正常。

在这种情况下,我得到的最好结果是:

return myEnumerable.Any() ? myEnumerable.First() : mySpecialValue;

但是这里我有多个 myEnumerable 枚举!

我该怎么做?我宁愿避免必须捕获任何异常。

最佳答案

您可以使用 DefaultIfEmpty 的重载指定您的回退值。那么你也不需要 FirstOrDefault 但你可以安全地使用 First:

return myEnumerable.DefaultIfEmpty(mySpecialValue).First();

关于c# - IEnumerable 上的 FirstOrDefault 具有不可为空的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31069013/

相关文章:

c# - NetworkStream Read 在死亡之前会等待多长时间?

c# - Discord Bot [C#] 不执行命令

c# - ViewBag 抛出 NullReferenceException(对象未发送到实例)

c# - 如何判断某物是否为 IEnumerable<>?

c# - 为什么要编写自定义 LINQ 提供程序?

c# - 在没有 foreach 循环的情况下使用 IEnumerable

c# - 如何使用 LINQ 合并来自多个 IEnumerable<T> 的结果

c# - RichTextBox 中的摄氏度符号

c# - WCF - 使用 DataMember 装饰 IEnumerable<T> 导致异常 :The underlying connection was closed: The connection was closed unexpectedly

c# - 在 C# 中销毁结构对象?