c# - 未找到匹配项时从 List<> 返回默认值

标签 c# list

我正在尝试找到一种更简洁的方法来在找不到匹配项时返回默认值。下面显示了我为最好地证明我的问题而编写的示例,来自 LinqPad

所以基本上,如果给定的 Age 没有在列表 SingleOrDefault 中找到,则返回一个 null 正常。因此,我没有返回 null,而是从中选择最高的 Threshold,而不管 Age 值是多少。

然而,不是执行 if 或使用 ?? (空合并运算符) 是否有更简洁的方法来实现这一点?也许在 test 类的 Age 属性的 getset 中设置默认值?

void Main()
{
    var list = new List<test>()
    { 
        new test ( 55, 27 ),
        new test ( 56, 28),
        new test ( 57, 29),
        new test ( 59, 30),
        new test ( 60, 31) //60+
    };

    var res = list.SingleOrDefault(x => x.Age == 61);   

    if (res == null)
    {
        list.Max(l => l.Threshold).Dump();
    }
    else
    {
        res.Threshold.Dump();   
    }  
} 

class test
{
    public int Age 
    { 
        get;
        set;
    }   

    public int Threshold 
    {   
        get;
        set;
    }

    public test(int age, int threshold)
    {
        Age = age;
        Threshold = threshold;
    }
}

最佳答案

您可以使用 LINQ 的 DefaultIfEmpty():

var res = list.Where(x => x.Age == 61)
              .Select(t => t)
              .DefaultIfEmpty(list.First(x => x.Threshold == list.Max(t => t.Threshold)))
              .SingleOrDefault();

关于c# - 未找到匹配项时从 List<> 返回默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56448141/

相关文章:

c# - 从数据库逐行写入数据到文本框

list - Erlang 记录项列表

list - 证明流的平等

c# - 具有两个在 EF 6 中工作的联接的 LINQ 查询在 EF 7 中给出错误

java - 从 Integer java 列表的列表中查找第一个元素

python - 如何将 turtle 的 y 坐标提取为 float - Python 3.x

以 Python 方式将多个值插入列表

c# - 调整大小和存储图像但锁定以确保它只完成一次

c# - 对象无法序列化,因为它没有无参数构造函数

c# - 如何在 JavaScript 脚本标记中使用 Razor for 循环?