当FirstOrDefault在排序列表中找不到任何内容时,我怎么能理解呢
本文关键字:能理解 任何内 FirstOrDefault 排序 列表 找不到 | 更新日期: 2023-09-27 18:00:05
我有SortedList<DateTime, object>
。其中的每一次都是一个KeyValuePair<>
,它是一个结构体。那么,当方法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