Howto override List<T> Contains

UNeverNo picture UNeverNo · Dec 3, 2012 · Viewed 18.2k times · Source

I want to compare a property instead of the entire object using a List[MyObject]. I therefore use IEquatable[MyObject] but the compiler still wants MyObject instead of the string property. Why?

Here is what I got:

public class AnyClass
{
    public List<AnyOtherClass> MyProperty { get; set; }        
    public string AnyProperty { get; set; }

    public AnyClass(string[] Names, string[] Values, string AnyProperty)
    {
        this.AnyProperty = AnyProperty;
        this.MyProperty = new List<AnyOtherClass>();
        for (int i = 0; i < Names.Length; i++)
            MyProperty.Add(new AnyOtherClass(Names[i], Values[i]));
    }
}

public class AnyOtherClass : IEquatable<string>
{
    public AnyOtherClass(string Name, string Values)
    {
        this.Name = Name;
        this.Values = Values.Split(';').ToList();
    }

    public string Name { get; set; }
    public List<string> Values { get; set; }

    public bool Equals(string other)
    {
        return this.Name.Equals(other);
    }
}

    private void DoSomething()
    {
        string[] Names = new string[] { "Name1", "Name2" };
        string[] Values = new string[] { "Value1_1;Value1_2", "Value2" };
        AnyClass ac = new AnyClass(Names, Values, "any Property");

        if (ac.MyProperty.Contains("Name1")) //Problem is here...
            //do something
    }

Answer

Pacane picture Pacane · Dec 3, 2012

You might want to try using this :

myList.Any(x => x.someProperty == someValue);

from MSDN : http://msdn.microsoft.com/en-us/library/bb534972.aspx

Determines whether any element of a sequence satisfies a condition.

The x => x.someProperty == someValue is called a lambda expression in case you didn't know.

And note that you can use this on anything implementing IEnumerable, so that doesn't restrict you to List<T>.