Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Func<> getting the parameter info

Tags:

c#

lambda

func

How to get the value of the passed parameter of the 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 value of query inside the Filter extension method assigned to _target

like image 574
Vincent Dagpin Avatar asked Jul 17 '13 06:07

Vincent Dagpin


People also ask

What is Func <> C#?

Func is a delegate that points to a method that accepts one or more arguments and returns a value. Action is a delegate that points to a method which in turn accepts one or more arguments but returns no value. In other words, you should use Action when your delegate points to a method that returns void.

What is func t TResult?

Func<T, TResult> defines a function that accepts one parameter (of type T) and returns an object (of type TResult). In your case, if you want a function that takes a Person object and returns a string...you'd want Func<Person, string> which is the equivalent of: string Function(Person p) { return p.Name; }

What is func in C# with example?

C# Func simple example string GetMessage() { return "Hello there!"; } Func<string> sayHello = GetMessage; Console. WriteLine(sayHello()); In the example, we use the Func delegate which has no parameters and returns a single value. This is the function to which we refer with the help of the Func delegate.


1 Answers

If you want to get the parameter you will have to pass expression. By passing a "Func" you will pass the compiled lambda, so you cannot access the expression tree any more.

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
like image 154
Fried Avatar answered Sep 27 '22 20:09

Fried