使用LINQ或以其他方式,你如何检查是否所有列表项具有相同的价值和回报,或返回“otherValue”如果他们不? [英] Using linq or otherwise, how do check if all list items have the same value and return it, or return an “otherValue” if they don’t?

查看:75
本文介绍了使用LINQ或以其他方式,你如何检查是否所有列表项具有相同的价值和回报,或返回“otherValue”如果他们不?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果列表中的所有项目具有相同的价值,我需要使用的值,否则我需要使用otherValue。我想不出这样做的简单明了的方式。

又见<一个href=\"http://stackoverflow.com/questions/4390232/neat-way-to-write-loop-that-has-special-logic-for-the-first-item-in-a-collection\">Neat方式来写循环,对集合中的第一项特殊的逻辑。


解决方案

  VAR VAL = yyy.First()值。
返回yyy.All(X =&GT; x.Value == VAL)? VAL:otherValue;

我能想到的最彻底的方法。您可以通过内联VAL使之成为一个班轮,但首先()将进行评估n次,增加一倍的执行时间。

要合并在评论中规定的空集的行为,你只要上述两个前增加一个行

 如果(YYY == NULL || yyy.Any()!)返回otherValue;

If all the items in a list have the same value, I need to use that value, otherwise I need to use an "otherValue". I can’t think of a simple and clear way of doing this.

see also Neat way to write loop that has special logic for the first item in a collection.

解决方案

var val = yyy.First().Value;
return yyy.All(x=>x.Value == val) ? val : otherValue; 

Cleanest way I can think of. You can make it a one-liner by inlining val, but First() would be evaluated n times, doubling execution time.

To incorporate the "empty set" behavior specified in the comments, you simply add one more line before the two above:

if(yyy == null || !yyy.Any()) return otherValue;

这篇关于使用LINQ或以其他方式,你如何检查是否所有列表项具有相同的价值和回报,或返回“otherValue”如果他们不?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆