如果列表中的所有项都具有相同的值,那么我需要使用该值,否则我需要使用"otherValue".我想不出一个简单明了的做法.
Kei*_*thS 144
var val = yyy.First().Value;
return yyy.All(x=>x.Value == val) ? val : otherValue; 
我能想到的最干净的方式.您可以通过内联val使其成为单行,但First()将被评估n次,执行时间加倍.
要合并评论中指定的"空集"行为,您只需在上述两个行之前再添加一行:
if(yyy == null || !yyy.Any()) return otherValue;
Jer*_*ell 91
所有平等的快速测试:
collection.Distinct().Count() == 1
Eri*_*ert 20
虽然您当然可以使用现有的序列运算符构建这样的设备,但在这种情况下,我倾向于将此编写为自定义序列运算符.就像是:
// 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>练习.:-)
Jus*_*ner 13
return collection.All(i => i == collection.First())) 
    ? collection.First() : otherValue;.
或者,如果您担心为每个元素执行First()(这可能是一个有效的性能问题):
var first = collection.First();
return collection.All(i => i == first) ? first : otherValue;
| 归档时间: | 
 | 
| 查看次数: | 88756 次 | 
| 最近记录: |