在List <struct>上执行LINQ操作

Sae*_*ani 3 c# linq

我有这样的结构

public struct MyStruct
{
     public string Name;
     //More fields and construtors
}
Run Code Online (Sandbox Code Playgroud)

现在,如果我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
Run Code Online (Sandbox Code Playgroud)

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

Raf*_*fal 12

尝试Any()LiNQ中的方法:

using System.Linq;

if(_myStructList.Any(x => x.Name == "DAMN!")) ...
Run Code Online (Sandbox Code Playgroud)

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


Cle*_*ens 5

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

if (_myStructList.Exists(x => x.Name == "DAMN!")) ...
Run Code Online (Sandbox Code Playgroud)