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?!

Dumbo
  • 13,555
  • 54
  • 184
  • 288
  • 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 – Dumbo 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,069
  • 7
  • 37
  • 47
Rafal
  • 12,391
  • 32
  • 54
5

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

if (_myStructList.Exists(x => x.Name == "DAMN!")) ...
Clemens
  • 123,504
  • 12
  • 155
  • 268