Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Use object's property rather than reference for List.Contains()

Tags:

c#

list

I have something like:

public class MyClass
{
  public string Type { get; set; }
  public int Value { get; set; }
}

and then I have:

List<MyClass> myList = new List<MyClass>()

// ... Populate myList

if (myList.Contains("testType"))
{
  // Do something
}

In the above code, I want myList.Contains() to match on the Type property rather than the MyClass object reference. How do I achieve this? Do I use the IComparable or ICompare interface, do I override MyClass.Equals(), or is it sufficient to override the string cast of MyClass?

Edit: After doing some tests with overriding Equals() and the string cast of MyClass, implementing ICompare and IComparable, I have found that none of these methods work. Actually, it seems like what would work is if I were to override the MyClass cast of string, something like myList.Contains((MyClass)"testType"). However I think I like The Scrum Meister's answer better :)

like image 541
Ozzah Avatar asked Jul 01 '11 01:07

Ozzah


1 Answers

You can use the Any extension method:

if (myList.Any(x => x.Type == "testType"))
{
  // Do something
}
like image 121
The Scrum Meister Avatar answered Oct 12 '22 22:10

The Scrum Meister