Haedrian Haedrian - 9 days ago 5
C# Question

Using List<>.Contains() with different type

I have a generic-ed list of a custom type

List<MyType> list = new List<MyType>();


I've overridden the .Equals of MyType so that it works if you compare a string or a MyType to it. My question is - is there a way of using List.Contains(string) if the List only contains MyType?

I realise there are other ways I can do it (such as creating a MyType object there and then instead of the string), but is there a way of doing it without having to extend List?

Answer

Use linq:

bool hasSugar = list.Any(i => i.Equals("sugar"));