Class order {
Guid Id;
int qty;
}
使用LINQ表达式,如何验证列表中所有订单的qty
是否相同?
提前致谢!
答案 0 :(得分:21)
您可以使用GroupBy
:
bool allEqual = orders.GroupBy(o => o.qty).Count() == 1;
或者,效率更高但可读性更低:
bool allEqual = !orders.GroupBy(o => o.qty).Skip(1).Any();
或者,使用Enumerable.All
确实更有效率:
int firstQty = orders.First().qty; // fyi: throws an exception on an empty sequence
bool allEqual = orders.All(o => o.qty == firstQty);
答案 1 :(得分:0)
如果只是为了提高可读性,我会添加扩展方法。
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;
}
}
调用:
var qtyEqual = orders.Select(order => order.qty).AllEqual();