我有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/