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 :)
You can use the Any
extension method:
if (myList.Any(x => x.Type == "testType"))
{
// Do something
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With