c# - 当 FirstOrDefault 在排序列表中找不到任何内容时,我如何理解?

标签 c#

我有SortedList<DateTime, object> .每一次都是一个KeyValuePair<>这是一个结构。那么,我如何理解 when 方法 FirstOrDefault在此列表中未找到任何内容?(对于类它返回 null 但对于 struct ?)

为什么我就是不能比较default(KeyValuePair<Key, Value>)FirstOrDefault 的结果?

private SortedList<DateTime, GatewayPassage> gwPassages = 
    new SortedList<DateTime, GatewayPassage>(new DescDateTimeComparer());

var lastGwPassages = gwPassages.FirstOrDefault(x => x.Value.Tag == tag &&
                                                    x.Value.Gateway == gateway);

我想要像“如果什么都没找到”这样的条件

if(lastGwPassages == %some kind of default value%)

最佳答案

将元素转换到 KeyValuePair<DateTime,object>? 中然后您将能够检查它是否等于 null。

SortedList<DateTime, object> collection = new SortedList<DateTime, object>()
{
    {  new DateTime(2016,1,2), new object() },
    {  new DateTime(2016,1,1), new object() },
    {  new DateTime(2016,1,3), new object() },
};

var firstOrDefault = collection.Cast<KeyValuePair<DateTime,object>?>().FirstOrDefault(); // date of 1/1/2016
var checkIfDefault = firstOrDefault == null; // false

collection.Clear();

firstOrDefault = collection.Cast<KeyValuePair<DateTime, object>?>().FirstOrDefault(); // null
checkIfDefault = firstOrDefault == null; // true

在您的示例代码中:

var lastGwPassages = gwPassages.Cast<KeyValuePair<DateTime,GatewayPassage>?>()
                               .FirstOrDefault(x => x.Value.Tag == tag &&
                                                    x.Value.Gateway == gateway);

现在你可以做 lastGwPassages == null

关于c# - 当 FirstOrDefault 在排序列表中找不到任何内容时,我如何理解?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38743970/

相关文章:

c# - 如何从 View 模型中弹出子窗口

c# - 如何计算这个奇数方法的时间复杂度

c# - 刷新两次picturebox显示错误图像

c# - 如何解决 Visual Studio 中的 CA 1009 警告

c# - 在c#中解析来自多个json数组的数据

c# - 在 C# 中使用表达式访问结构属性

c# - 如何从按钮中获取文件

c# - 如何在 Unity3D 中使用 C++ dll?

c# - WPF/数据网格 : Binding to different properties for displaying and editing

C# 无法动态生成这个简单的事件处理程序