Class order {
Guid Id;
int qty;
}
Using LINQ expression, how can I verify if the qty
is the same for all orders in a list?
Thanks in advance!
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With