如果列表中的所有项目都具有相同的值,那么我需要使用该值,否则需要使用“otherValue”。我想不出一种简单明了的方法。当列表为空时,应返回“其他”值。
另请参阅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;

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

要合并注释中指定的“空集”行为,只需在上述两行之前添加一行:
if(yyy == null || !yyy.Any()) return otherValue;

10-04 22:29