Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

list

equals

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...?

like image 283
Sambo Avatar asked Mar 08 '10 01:03

Sambo


People also ask

What is using System collections generic in C#?

Collections. Generic Namespace. Contains interfaces and classes that define generic collections, which allow users to create strongly typed collections that provide better type safety and performance than non-generic strongly typed collections.

How do you check if a value exists in a list C#?

public bool Contains (T item); Here, item is the object which is to be locate in the List<T>. The value can be null for reference types. Return Value: This method returns True if the item is found in the List<T> otherwise returns False.

How do you check if a string exists in a list C#?

if (myList. Contains(myString)) string element = myList. ElementAt(myList. IndexOf(myString));


1 Answers

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));
    }
}
like image 111
bkaid Avatar answered Oct 24 '22 18:10

bkaid