Func <> getting parameter information

How to get value of passed parameter Func<> Lambda in C #

 IEnumerable<AccountSummary> _data = await accountRepo.GetAsync(); string _query = "1011"; Accounts = _data.Filter(p => p.AccountNumber == _query); 

and this is my extension method

 public static ObservableCollection<T> Filter<T>(this IEnumerable<T> collection, Func<T, bool> predicate) { string _target = predicate.Target.ToString(); // i want to get the value of query here.. , i expect "1011" throw new NotImplementedException(); } 

I want to get the request value inside the filter extension method assigned by _target

+4
source share
3 answers

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 
+7
source

so instead of passing your predicate as Func<T,bool> pass an expression tree instead of Expression<Func<T,bool>

Then you can study the type of expression and get its component parts, this will not affect the way the method is called, you can still pass lambda to it.

+1
source

I really don't think you can do this. Check the following situation:

Your predicate is Func<T, bool> predicate , so you can call it like this:

 Accounts = _data.Filter(p => true); 

What would you like to receive from such a call?

(p) => true satisfies Func<T, bool> because it takes T as input and returns the value bool .

0
source

Source: https://habr.com/ru/post/1491785/


All Articles