2013-01-07 28 views
3

執行LINQ操作我有這樣上列出<struct>

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

一個struct現在,如果我有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

你似乎缺少一個右括號的,如果? – lahsrah

+0

這只是一個錯字,我的實際代碼是語法錯誤!感謝您指出 –

+0

Contains需要一個'MyStruct'的實例,它需要重寫的相等比較才能匹配。根據Rafal的回答,使用'Any'將會是更好的解決方案。 – SpaceBison

回答

4

到Enumerable.Any另一種不使用Linq是List.Exists

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

嘗試在LINQ的Any()方法:

using System.Linq; 

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

Contains()List<>聲明的方法,它期待一個對象作爲參數,並使用等於比較的對象。