Sambo
Sambo

Reputation: 1472

Equals method of System.Collections.Generic.List<T>...?

I'm creating a class that derives from List...

public class MyList : List<MyListItem> {}

I've overridden Equals of MyListItem...

public override bool Equals(object obj)
{
    MyListItem li = obj as MyListItem;
    return (ID == li.ID);  // ID is a property of MyListItem
}

I would like to have an Equals method in the MyList object too which will compare each item in the list, calling Equals() on each MyListItem object.

It would be nice to simply call...

MyList l1 = new MyList() { new MyListItem(1), new MyListItem(2) };
MyList l2 = new MyList() { new MyListItem(1), new MyListItem(2) };

if (l1 == l2)
{
    ...
}

...and have the comparisons of the list done by value.

What's the best way...?

Upvotes: 17

Views: 17593

Answers (2)

bkaid
bkaid

Reputation: 52073

You can use the Linq method SequenceEqual on the list since your list implements IEnumerable. This will verify all the elements are the same and in the same order. If the order may be different, you could sort the lists first.

Here's a minimal example:

using System;
using System.Collections.Generic;
using System.Linq; // for .SequenceEqual

class Program {
    static void Main(string[] args) {
        var l1 = new List<int>{1, 2, 3};
        var l2 = new List<int>{1, 2, 3};
        var l3 = new List<int>{1, 2, 4};
        Console.WriteLine("l1 == l2? " + l1.SequenceEqual(l2));
        Console.WriteLine("l1 == l3? " + l1.SequenceEqual(l3));
    }
}

Upvotes: 33

Amit
Amit

Reputation: 19

public class MyList<T> : List<T>
{
    public override bool Equals(object obj)
    {
        if (obj == null)
            return false;

        MyList<T> list = obj as MyList<T>;
        if (list == null)
            return false;

        if (list.Count != this.Count)
            return false;

        bool same = true;
        this.ForEach(thisItem =>
        {
            if (same)
            {
                same = (null != list.FirstOrDefault(item => item.Equals(thisItem)));
            }
        });

        return same;
    }
}

Upvotes: 1

Related Questions