如果列表中的所有项都有相同的值,那么我需要使用该值,否则我需要使用“otherValue”。我想不出一个简单明了的方法来做这件事。当列表为空时,它应该返回"other“值。
另请参阅Neat way to write loop that has special logic for the first item in a collection.
发布于 2010-12-09 01:32:49
var val = yyy.First().Value;
return yyy.All(x=>x.Value == val) ? val : otherValue;
我能想到的最干净的方式。您可以通过内联val来使其成为一行程序,但是First()将被计算n次,从而使执行时间加倍。
要合并注释中指定的“空集”行为,只需在上述两行之前再添加一行即可:
if(yyy == null || !yyy.Any()) return otherValue;
发布于 2011-04-01 02:52:00
对所有平等的人进行快速测试:
collection.Distinct().Count() == 1
发布于 2010-12-09 02:24:51
虽然您当然可以使用现有的序列操作符构建这样的设备,但在这种情况下,我倾向于将此操作符编写为自定义序列操作符。类似于:
// 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>
的泛型方法作为练习。:-)
https://stackoverflow.com/questions/4390406
复制相似问题