If you want to get a parameter, you will need to pass an expression. Skipping "Func" will pass the compiled lambda so that you no longer have access to the expression tree.
public static class FilterStatic { // passing expression, accessing value public static IEnumerable<T> Filter<T>(this IEnumerable<T> collection, Expression<Func<T, bool>> predicate) { var binExpr = predicate.Body as BinaryExpression; var value = binExpr.Right; var func = predicate.Compile(); return collection.Where(func); } // passing Func public static IEnumerable<T> Filter2<T>(this IEnumerable<T> collection, Func<T, bool> predicate) { return collection.Where(predicate); } }
Testmethod
var accountList = new List<Account> { new Account { Name = "Acc1" }, new Account { Name = "Acc2" }, new Account { Name = "Acc3" }, }; var result = accountList.Filter(p => p.Name == "Acc2"); // passing expression var result2 = accountList.Filter2(p => p.Name == "Acc2"); // passing function
source share