Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if all values are equal in a list

Tags:

c#

lambda

linq

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!

like image 246
Chi Avatar asked Nov 11 '12 22:11

Chi


2 Answers

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); 
like image 153
Tim Schmelter Avatar answered Sep 18 '22 13:09

Tim Schmelter


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();
like image 45
rymdsmurf Avatar answered Sep 20 '22 13:09

rymdsmurf