Func <>获取参数信息

Vin*_*pin 7 c# lambda func

如何Func<>在C#中获取Lambda 的传递参数的值

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

这是我的扩展方法

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();
}
Run Code Online (Sandbox Code Playgroud)

我想在分配给_target的Filter扩展方法中获取查询的值

Fri*_*ied 11

如果要获取参数,则必须传递表达式.通过传递"Func",您将传递已编译的lambda,因此您无法再访问表达式树.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

测试方法

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
Run Code Online (Sandbox Code Playgroud)