3

I have a struct like this

public struct MyStruct
{
     public string Name;
     //More fields and construtors
}

Now if I have List<MyStruct> is there a way to use the Contains() feature of list?

This does not compile:

if(_myStructList.Contains(x => x.Name == "DAMN!")){//DO STUFF}

Here is the error:

Cannot convert lambda expression to type 'MyStruct' because it is not a delegate type

I guess then this is not gonna work with structs?!

Saeid Yazdani
  • 12,365
  • 48
  • 158
  • 270
  • 2
    You seem to be missing a closing bracket for the if? – lahsrah Jan 07 '13 at 12:55
  • That was just a typo in the question, actual code I have is syntax error free! Thanks for pointing out though – Saeid Yazdani Jan 07 '13 at 12:56
  • Contains expects an instance of `MyStruct` which will need overridden equality comparison to match. Using `Any` would be a better solution as per Rafal's answer. – SpaceBison Jan 07 '13 at 12:58
  • To aid future searches, the error text reported in this question corresponds to error code **CS1660**. – DavidRR Feb 19 '14 at 20:29

2 Answers2

13

Try the Any() method in LiNQ:

using System.Linq;

if(_myStructList.Any(x => x.Name == "DAMN!")) ...

Contains() is a declared method of List<> and it expects an object as a parameter and uses equals to compare the objects.

Brian
  • 5,064
  • 7
  • 33
  • 44
Rafal
  • 11,105
  • 26
  • 49
5

An alternative to Enumerable.Any that doesn't use Linq is List.Exists:

if (_myStructList.Exists(x => x.Name == "DAMN!")) ...
Clemens
  • 110,214
  • 10
  • 133
  • 230