HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Checking two lists for equal items

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
equalcheckingtwoitemsforlists

Problem

I'm using this code for checking if two List are equal or not:

public static bool EqualsAll(this IList a, IList b)
{
    if (a == null || b == null)
        return (a == null && b == null);

    if (a.Count != b.Count)
        return false;

    EqualityComparer comparer = EqualityComparer.Default;

    for (int i = 0; i < a.Count; i++)
    {
        if (!comparer.Equals(a[i], b[i]))
            return false;
    }

    return true;
}


Now assume that I'm using this code for checking two big lists. Is this code efficient?

Solution

Checking whether two lists are equal is naturally an O(n) operation. So yes, your code looks efficient.

Note that you could also replace your for loop with Enumerable.SequenceEqual

public static bool EqualsAll(this IList a, IList b)
{
    if (a == null || b == null)
        return (a == null && b == null);

    if (a.Count != b.Count)
        return false;

    return a.SequenceEqual(b);
}


If you take a look at its implementation, you'll notice that it's very similar to yours. It might be just a tiny bit less efficient - so if performance is an issue here, measure both approaches, and then weigh readability/maintainability vs performance gains.

On a different note, I would rename the method to SequenceEqual and consider it a "specialization" of Enumerable.SequenceEqual for lists.

I would also consider throwing an exception if either argument is null.
This would be consistent with the BCL's own extension methods (Select, Where, ToList, SequenceEqual, Any, All, etc).

Code Snippets

public static bool EqualsAll<T>(this IList<T> a, IList<T> b)
{
    if (a == null || b == null)
        return (a == null && b == null);

    if (a.Count != b.Count)
        return false;

    return a.SequenceEqual(b);
}

Context

StackExchange Code Review Q#104779, answer score: 15

Revisions (0)

No revisions yet.