Check if all values are equal in a list
You can use GroupBy
:
bool allEqual = orders.GroupBy(o => o.qty).Count() == 1;
or, little bit more efficient but less readable:
bool allEqual = !orders.GroupBy(o => o.qty).Skip(1).Any();
or, definitely more efficient using Enumerable.All
:
int firstQty = orders.First().qty; // fyi: throws an exception on an empty sequence
bool allEqual = orders.All(o => o.qty == firstQty);
I would add an extension method, if only to improve readability.
public static bool AllEqual<T>(this IEnumerable<T> source, IEqualityComparer<T> comparer = null)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
comparer = comparer ?? EqualityComparer<T>.Default;
using (var enumerator = source.GetEnumerator())
{
if (enumerator.MoveNext())
{
var value = enumerator.Current;
while (enumerator.MoveNext())
{
if (!comparer.Equals(enumerator.Current, value))
return false;
}
}
return true;
}
}
Calling it:
var qtyEqual = orders.Select(order => order.qty).AllEqual();