如何检查所有列表项是否具有相同的值并将其返回,或者如果没有,则返回"otherValue"? [英] How to check if all list items have the same value and return it, or return an “otherValue” if they don’t?

查看:54
本文介绍了如何检查所有列表项是否具有相同的值并将其返回,或者如果没有,则返回"otherValue"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果列表中的所有项目都具有相同的值,那么我需要使用该值,否则需要使用"otherValue".我想不出一种简单明了的方法.

If all the items in a list have the same value, then 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.

另请参见推荐答案

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

我能想到的最干净的方法.您可以通过内联val使其成为单线,但是First()将被评估n次,从而使执行时间加倍.

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;

这篇关于如何检查所有列表项是否具有相同的值并将其返回,或者如果没有,则返回"otherValue"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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