Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method with Predicate as Parameter

This is a general question, but here is the specific case I'm looking for a solution to:

I have a Dictionary<int, List<string>> I want to apply various predicates to. I want one method that can take care of multiple LINQ queries such as these:

from x in Dictionary
where x.Value.Contains("Test")
select x.Key

from x in Dictionary
where x.Value.Contains("Test2")
select x.Key

So I'm looking for a method like so:

public int GetResult(**WhatGoesHere** filter)
{
    return from x in Dictionary.Where(filter)
           select x.Key;
}

To be used like so:

int result;

result = GetResult(x => x.Value.Contains("Test"));
result = GetResult(x => x.Value.Contains("Test2"));

What is the proper syntax for WhatGoesHere?

like image 300
Ocelot20 Avatar asked Aug 03 '10 19:08

Ocelot20


People also ask

Can predicate be passed as method parameters?

Predicates can be passed as method parameters. In the example, we pass a predicate function as the second parameter to the eval method.

What is a predicate method?

The predicate is a predefined functional interface in Java defined in the java. util. Function package. It helps with manageability of code, aids in unit-testing, and provides various handy functions.

How do you pass a method name as a parameter in Java?

Pass a Method as a Parameter by Using the lambda Function in Java. This is a simple example of lambda, where we are using it to iterate the ArrayList elements. Notice that we're passing the lambda function to the forEach() method of the Iterable interface. The ArrayList class implements the Iterable interface.


1 Answers

You can use Func<KeyValuePair<int, List<string>>, bool>:

public int GetResult(Func<KeyValuePair<int, List<string>>, bool> filter)
{
    return (from x in Dictionary
            where filter(x)
            select x.Key).FirstOrDefault();
}

Or alternatively: Predicate<KeyValuePair<int, List<string>>>. I think Func which was introduced in .NET 3.5 is preferred these days.

You are using x to mean two different things in your final example and this will give a compile error. Try changing one of the xs to something else:

x = GetResult(y => y.Value.Contains("Test1"));
like image 200
Mark Byers Avatar answered Oct 14 '22 07:10

Mark Byers