首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何检查所有列表项是否都具有相同的值并返回它,如果不是,则返回“otherValue”?

如何检查所有列表项是否都具有相同的值并返回它,如果不是,则返回“otherValue”?
EN

Stack Overflow用户
提问于 2010-12-09 01:29:21
回答 9查看 121.7K关注 0票数 140

如果列表中的所有项都有相同的值,那么我需要使用该值,否则我需要使用“otherValue”。我想不出一个简单明了的方法来做这件事。当列表为空时,它应该返回"other“值。

另请参阅Neat way to write loop that has special logic for the first item in a collection.

EN

回答 9

Stack Overflow用户

回答已采纳

发布于 2010-12-09 01:32:49

代码语言:javascript
复制
var val = yyy.First().Value;
return yyy.All(x=>x.Value == val) ? val : otherValue; 

我能想到的最干净的方式。您可以通过内联val来使其成为一行程序,但是First()将被计算n次,从而使执行时间加倍。

要合并注释中指定的“空集”行为,只需在上述两行之前再添加一行即可:

代码语言:javascript
复制
if(yyy == null || !yyy.Any()) return otherValue;
票数 176
EN

Stack Overflow用户

发布于 2011-04-01 02:52:00

对所有平等的人进行快速测试:

代码语言:javascript
复制
collection.Distinct().Count() == 1
票数 116
EN

Stack Overflow用户

发布于 2010-12-09 02:24:51

虽然您当然可以使用现有的序列操作符构建这样的设备,但在这种情况下,我倾向于将此操作符编写为自定义序列操作符。类似于:

代码语言:javascript
复制
// Returns "other" if the list is empty.
// Returns "other" if the list is non-empty and there are two different elements.
// Returns the element of the list if it is non-empty and all elements are the same.
public static int Unanimous(this IEnumerable<int> sequence, int other)
{
    int? first = null;
    foreach(var item in sequence)
    {
        if (first == null)
            first = item;
        else if (first.Value != item)
            return other;
    }
    return first ?? other;
}

这非常清楚,简短,涵盖了所有情况,并且不会不必要地创建序列的额外迭代。

将其转换为适用于IEnumerable<T>的泛型方法作为练习。:-)

票数 23
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4390406

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档