Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a predicate as parameter c#

How can I pass a predicate into a method but also have it work if no predicate is passed? I thought maybe something like this, but it doesn't seem to be correct.

private bool NoFilter() { return true; }

private List<thing> GetItems(Predicate<thing> filter = new Predicate<thing>(NoFilter))
{
    return rawList.Where(filter).ToList();
}
like image 703
davecove Avatar asked Jun 26 '17 13:06

davecove


People also ask

How do you pass a function as a parameter in C#?

If we want to pass a function that does not return a value, we have to use the Action<> delegate in C#. The Action<T> delegate works just like the function delegate; it is used to define a function with the T parameter. We can use the Action<> delegate to pass a function as a parameter to another function.

How do you pass a function as a parameter?

Function Call When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this: func(print); would call func , passing the print function to it.

Can you pass a class as a parameter in C++?

Passing and Returning Objects in C++ In C++ we can pass class's objects as arguments and also return them from a function the same way we pass and return other variables.


1 Answers

private List<thing> GetItems(Func<thing, bool> filter = null)
{
    return rawList.Where(filter ?? (s => true)).ToList();
}

In this expression s => true is the fallback filter which is evaluated if the argument filter is null. It just takes each entry of the list (as s) and returns true.

like image 179
Waescher Avatar answered Sep 23 '22 20:09

Waescher