Creating a Lambda Contains expression
I want to create a class which wraps a list of structures.
I have the following code:
public struct MyData
{
public int ID;
public string Description;
}
public class MyClass
{
private List<MyData> data;
public bool Contains(string desc)
{
if (data != null)
{
return data.Contains(item => item.Description.Contains(desc));
}
return false;
}
}
I can't see why I'm unable to use a Lambda expression, the er开发者_如何学编程ror that I get is:
Cannot convert lambda expression to type 'MyApp.MyData' because it is not a delegate type
In your case Contains expects you to pass it a MyData
, if you want to use a lambda for comparison then use Any
return data.Any(item => item.Description.Contains(desc));
public bool Contains( string desc )
{
return data != null && data.Exists( item => item.Description.Contains( desc ) );
}
The reason is because the List<T>Contains
method expects a T
, whereas you've given it a lambda expression, created with the =>
.
What you could do is:
data.Any(item => item.Description.Contains(desc));
精彩评论