我正在尝试找到一种更简洁的方法来在找不到匹配项时返回默认值。下面显示了我为最好地证明我的问题而编写的示例,来自 LinqPad
所以基本上,如果给定的 Age
没有在列表 SingleOrDefault
中找到,则返回一个 null
正常。因此,我没有返回 null
,而是从中选择最高的 Threshold
,而不管 Age
值是多少。
然而,不是执行 if
或使用 ?? (空合并运算符)
是否有更简洁的方法来实现这一点?也许在 test
类的 Age 属性的 get
和 set
中设置默认值?
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/