Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/react-native/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从列表返回默认值<&燃气轮机;当未找到匹配项时_C#_List - Fatal编程技术网

C# 从列表返回默认值<&燃气轮机;当未找到匹配项时

C# 从列表返回默认值<&燃气轮机;当未找到匹配项时,c#,list,C#,List,我试图找到一种更干净的方法,在没有找到匹配项时返回默认值。下面的LinqPad 因此,如果在列表中找不到给定的Age,则基本上SingleOrDefault会正常返回null。因此,无论Age值是多少,我都从中选择最高的阈值,而不是返回null 但是,不是执行if或使用??(空合并运算符)是否有更干净的方法实现此目的?也许在test类中的年龄属性的get和set中设置默认值 void Main() { var list = new List<test>() {

我试图找到一种更干净的方法,在没有找到匹配项时返回默认值。下面的
LinqPad

因此,如果在列表中找不到给定的
Age
,则基本上
SingleOrDefault
会正常返回
null
。因此,无论
Age
值是多少,我都从中选择最高的
阈值,而不是返回
null

但是,不是执行
if
或使用
??(空合并运算符)
是否有更干净的方法实现此目的?也许在
test
类中的年龄属性的
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;
    }
}
void Main()
{
var list=新列表()
{ 
新测试(55,27),
新测试(56,28),
新测试(57,29),
新测试(59,30),
新测试(60,31)//60+
};
var res=list.SingleOrDefault(x=>x.Age==61);
如果(res==null)
{
list.Max(l=>l.Threshold.Dump();
}
其他的
{
res.Threshold.Dump();
}  
} 
课堂测试
{
公共信息
{ 
得到;
设置
}   
公共整数阈值
{   
得到;
设置
}
公共测试(整数年龄,整数阈值)
{
年龄=年龄;
阈值=阈值;
}
}

您始终可以使用扩展方法,尽管这似乎有点过头了

public static Test SingleAgeOrMaxThreshold(this IEnumerable<Test> items, int age)
{
    Test max = null;
    foreach (Test t in items)
    {
        if (t.Age == age)
            return t;

        if (max == null || t.Threshold > max.Threshold)
            max = t;
    }

    return max;
}
publicstatictestsingleageorexthreshold(此IEnumerable items,int-age)
{
测试最大值=空;
foreach(测试项目中的t)
{
如果(t.Age==年龄)
返回t;
如果(max==null | | t.阈值>max.阈值)
max=t;
}
返回最大值;
}

您始终可以使用扩展方法,尽管这似乎有点过头了

public static Test SingleAgeOrMaxThreshold(this IEnumerable<Test> items, int age)
{
    Test max = null;
    foreach (Test t in items)
    {
        if (t.Age == age)
            return t;

        if (max == null || t.Threshold > max.Threshold)
            max = t;
    }

    return max;
}
publicstatictestsingleageorexthreshold(此IEnumerable items,int-age)
{
测试最大值=空;
foreach(测试项目中的t)
{
如果(t.Age==年龄)
返回t;
如果(max==null | | t.阈值>max.阈值)
max=t;
}
返回最大值;
}

您可以使用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();

您可以使用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();

我想您希望有一个LINQ方法
SingleOrMax
,可以这样使用:

var res = list.SingleOrMax(x => x.Age == 61, x => x.Threshold);
第一个表达式是
SingleOrDefault
的谓词,第二个表达式选择用于查找max元素的键(如果需要)

这是:

public static TSource SingleOrMax<TSource, TMaxKey>(this IEnumerable<TSource> source,
    Func<TSource, bool> predicate, Func<TSource, TMaxKey> maxKeySelector)
{
    var result = source.SingleOrDefault(predicate);
    if (result != default) return result;
    var maxKeyComparer = Comparer<TMaxKey>.Default;
    TSource max = default;
    TMaxKey maxKey = default;
    int count = 0;
    foreach (var item in source)
    {
        var key = maxKeySelector(item);
        if (count == 0 || maxKeyComparer.Compare(key, maxKey) > 0)
        {
            max = item;
            maxKey = key;
        }
        count++;
    }
    // If you remove the line bellow, then rename this method to SingleOrMaxOrDefault
    if (count == 0) throw new InvalidOperationException("Sequence contains no elements");
    return max;
}
publicstatictsource SingleOrMax(此IEnumerable源、,
Func谓词,Func maxKeySelector)
{
var result=source.SingleOrDefault(谓词);
if(result!=默认值)返回结果;
var maxkeycomarer=Comparer.Default;
TSource max=默认值;
TMaxKey maxKey=默认值;
整数计数=0;
foreach(源中的var项)
{
var键=maxKeySelector(项目);
if(count==0 | | maxkeycomarer.Compare(key,maxKey)>0)
{
最大值=项目;
maxKey=key;
}
计数++;
}
//如果删除下面的行,则将此方法重命名为SingleOrmaxOrderFault
如果(计数=0)抛出新的InvalidOperationException(“序列不包含元素”);
返回最大值;
}

我想您希望有一个LINQ方法
SingleOrMax
,您可以这样使用:

var res = list.SingleOrMax(x => x.Age == 61, x => x.Threshold);
第一个表达式是
SingleOrDefault
的谓词,第二个表达式选择用于查找max元素的键(如果需要)

这是:

public static TSource SingleOrMax<TSource, TMaxKey>(this IEnumerable<TSource> source,
    Func<TSource, bool> predicate, Func<TSource, TMaxKey> maxKeySelector)
{
    var result = source.SingleOrDefault(predicate);
    if (result != default) return result;
    var maxKeyComparer = Comparer<TMaxKey>.Default;
    TSource max = default;
    TMaxKey maxKey = default;
    int count = 0;
    foreach (var item in source)
    {
        var key = maxKeySelector(item);
        if (count == 0 || maxKeyComparer.Compare(key, maxKey) > 0)
        {
            max = item;
            maxKey = key;
        }
        count++;
    }
    // If you remove the line bellow, then rename this method to SingleOrMaxOrDefault
    if (count == 0) throw new InvalidOperationException("Sequence contains no elements");
    return max;
}
publicstatictsource SingleOrMax(此IEnumerable源、,
Func谓词,Func maxKeySelector)
{
var result=source.SingleOrDefault(谓词);
if(result!=默认值)返回结果;
var maxkeycomarer=Comparer.Default;
TSource max=默认值;
TMaxKey maxKey=默认值;
整数计数=0;
foreach(源中的var项)
{
var键=maxKeySelector(项目);
if(count==0 | | maxkeycomarer.Compare(key,maxKey)>0)
{
最大值=项目;
maxKey=key;
}
计数++;
}
//如果删除下面的行,则将此方法重命名为SingleOrmaxOrderFault
如果(计数=0)抛出新的InvalidOperationException(“序列不包含元素”);
返回最大值;
}

我不确定“cleaner”这个词是否会被用于表示一个解决方案,该解决方案分布在可能被查询的每个属性的所有getter和setter上。如果在其他一些关于年龄的查询中,期望的默认值恰好是完全不同的呢?在您的环境中,使用null合并运算符可能是最好的可读/可维护代码。请注意,您不能在一个易于读取/维护的查询中真正地结合这一点(换句话说:即使使用for/foreach循环也会产生更干净、可读性更好/可维护性更好的代码),因为必须首先完全迭代枚举,以确定是否确实存在一个匹配的“特定年龄”在决定是否应选择替代的“最大阈值”项目(基于与“特定年龄”项目不同的选择标准)之前,请选择该项目。这已被问了很多次,例如我不确定“更干净”这是我用来描述一个解决方案的术语,该解决方案分布在可能被查询的每个属性的所有getter和setter上。如果在其他一些关于年龄的查询中,期望的默认值恰好是完全不同的呢?在您的环境中,使用null合并运算符可能是最好的可读/可维护代码。请注意,您不能在一个易于阅读/维护的查询中真正地结合这一点(换句话说:即使使用for/foreach循环也会产生更干净、可读性更好/可维护性更好的代码),因为枚举必须首先在compl中迭代