I am writing a method that gets a lambda expression as a parameter to be used to filter the IList<SomeModel> _collection
.
public void DoSomething(SomeModel model)
{
FilterCollectionUsingPredicate(x => x.Name.Equals(model.Name));
}
private void FilterCollectionUsingPredicate(Func<SomeModel, bool> predicate)
{
_collection = _collection.Where(predicate).ToList();
}
It works well when the predicate
parameter is a simple expression, like x => x.Name.Equals(model.Name)
. However, it gets tricky when it has to use some other (local) collection and Contains
clause.
public void DoSomething(SomeModel model)
{
IEnumerable<string> someOtherCollection = model.SomeOtherCollection;
FilterCollectionUsingPredicate(x => someOtherCollection.Contains(x.Phone));
}
private void FilterCollectionUsingPredicate(Func<SomeModel, bool> predicate)
{
_collection = _collection.Where(predicate).ToList();
}
Of course, FilterCollectionUsingPredicate
method does not see someOtherCollection
and therefore, throws an error. Can someone explain how to properly define and use this function to handle such a case?
Well try and create a generic extension instead, Expression should keep track of all other data in the expression. Try and create the predicate as Expression
private void FilterCollectionUsingPredicate(Expression<Func<SomeModel, bool>> predicate)
{
_collection = _collection.Where(predicate).ToList();
}
It should work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.