如何检查所有列表项是否具有相同的值并返回它,或者返回一个“ other Value”(如果没有) ?

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

参见 编写对集合中的第一个项具有特殊逻辑的循环的简单方法。

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

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

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

if(yyy == null || !yyy.Any()) return otherValue;
return collection.All(i => i == collection.First()))
? collection.First() : otherValue;.

或者如果您担心对每个元素执行 First ()(这可能是一个有效的性能问题) :

var first = collection.First();
return collection.All(i => i == first) ? first : otherValue;
public int GetResult(List<int> list){
int first = list.First();
return list.All(x => x == first) ? first : SOME_OTHER_VALUE;
}

虽然您当然可以用现有的序列运算符构建这样一个设备,但是在这种情况下,我倾向于将这个设备作为一个自定义序列运算符来编写。比如:

// 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>上工作的通用方法留作练习。 : -)

对所有人来说都是很好的快速测试:

collection.Distinct().Count() == 1

这可能有点晚了,但是基于 Eric 的回答,这个扩展同样适用于值类型和引用类型:

public static partial class Extensions
{
public static Nullable<T> Unanimous<T>(this IEnumerable<Nullable<T>> sequence, Nullable<T> other, IEqualityComparer comparer = null)  where T : struct, IComparable
{
object first = null;
foreach(var item in sequence)
{
if (first == null)
first = item;
else if (comparer != null && !comparer.Equals(first, item))
return other;
else if (!first.Equals(item))
return other;
}
return (Nullable<T>)first ?? other;
}


public static T Unanimous<T>(this IEnumerable<T> sequence, T other, IEqualityComparer comparer = null)  where T : class, IComparable
{
object first = null;
foreach(var item in sequence)
{
if (first == null)
first = item;
else if (comparer != null && !comparer.Equals(first, item))
return other;
else if (!first.Equals(item))
return other;
}
return (T)first ?? other;
}
}

使用 LINQ 的另一种选择:

var set = new HashSet<int>(values);
return (1 == set.Count) ? values.First() : otherValue;

我发现对于多达6000个整数的列表,使用 HashSet<T>会比以下方法更快:

var value1 = items.First();
return values.All(v => v == value1) ? value1: otherValue;

与上述简化方法略有不同。

var result = yyy.Distinct().Count() == yyy.Count();

如果一个数组的类型是多维的,如下所示,那么我们必须在 linq 下面写入来检查数据。

例如: 这里的元素是0,我正在检查所有的值是否为0。
Ip1 =
0000
0000
0000
0000

    var value=ip1[0][0];  //got the first index value
var equalValue = ip1.Any(x=>x.Any(xy=>xy.Equals()));  //check with all elements value
if(equalValue)//returns true or false
{
return "Same Numbers";
}else{
return "Different Numbers";
}