【问题标题】:How I can understand when FirstOrDefault found nothing in sorted list?当 FirstOrDefault 在排序列表中找不到任何内容时,我如何理解?
【发布时间】:2016-08-03 12:40:13
【问题描述】:

我有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%)

【问题讨论】:

  • 如果要控制查找结果,为什么要使用FirstOfDefault?
  • 我觉得你应该和default(KeyValuePair&lt;T,U&gt;)比较
  • 你可以比较.Key == default(DateTime)
  • 您能否提供一些代码以确保我们正确理解您的问题?
  • 请提供更多实际代码。 default 值是实际数据中可以出现的值吗?

标签: c#


【解决方案1】:

将项目转换为KeyValuePair&lt;DateTime,object&gt;?,然后您将能够检查它是否等于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

【讨论】:

    猜你喜欢
    • 2015-05-24
    • 2018-05-11
    • 2015-03-17
    • 1970-01-01
    • 2015-12-24
    • 1970-01-01
    • 2017-07-24
    • 2021-04-13
    • 1970-01-01
    相关资源
    最近更新 更多