在List <struct> </struct>上执行LINQ操作

时间:2013-01-07 12:54:12

标签: c# linq

我有这样的结构

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

现在,如果我有List<MyStruct>,是否可以使用列表的Contains()功能?

这不编译:

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

这是错误:

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

我猜那么这不会与结构一起使用?!

2 个答案:

答案 0 :(得分:12)

尝试使用LiNQ中的Any()方法:

using System.Linq;

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

Contains()List<>的声明方法,它期望一个对象作为参数并使用equals来比较对象。

答案 1 :(得分:4)

不使用Linq的Enumerable.Any的替代方法是List.Exists

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