Where predicate and Expression<Func<T, bool>>
I have this line of code that returns index of particular object in a IList<T>
int index = list.IndexOf(list.Where(x => x.Code == searchValue).FirstOrDefault());
and I have similar construction on many places, which searches collections on different properties. My goal is to automate this, so I can have a generic method MyClass<T>
int index = myClass.Find<T>(x=> x.Code == searchValue);
or
int index = MyClass.Find<T>(x => x.Name.ToUpper().StartsWith(searchValue.ToUpper()));
Is this possible with Lambda expressions?
Edit:
For anyone that is asking the same, here is the code that is working:
public int Find(Func<T, bool> whereClause)
{
return _list.IndexOf(_list.Where<T>(whereClause).FirstOrDefaul开发者_如何学Ct<T>());
}
I'm not sure why you think you need to use an expression tree. Assuming list
is a List<T>
, you should be able to use FindIndex
:
int index = list.FindIndex(x => x.Code == searchValue);
If that's not what you need, please give us more information about what the types involved are.
精彩评论