Tony
Tony

Reputation: 12695

Func<> add an extra parameter dynamically

how can I add an extra parameter to my Func<> expression ? Something like:

Func<char, bool> myPredicate = (x) => (char.IsLetter(x) || x == 'X');

...

"abc".All(x => char.IsDigit(x) || myPredicate);

but I get an error

Operator '||' cannot be applied to operands of type 'bool' and Func< char, bool>

Upvotes: 2

Views: 119

Answers (2)

Mat&#237;as Fidemraizer
Mat&#237;as Fidemraizer

Reputation: 64923

Or, what about this other approach?

var text = "abc";

var predicates = new Func<char, bool>[] { 
    x => char.IsLetter(x) || x == 'X', 
    char.IsDigit 
};

var result = predicates.Any(text.All);

// Outputs TRUE 
Console.WriteLine(result);

Also, if you need to check many specific characters, you can create a charEquals with curried parameters:

var text = "abc";

// More type inference to generalize charEquals to just equals, please!
Func<char, Func<char, bool>> charEquals = ca => cb => ca == cb;

var predicates = new Func<char, bool>[] { 
    char.IsLetter, 
    charEquals('X'),
    charEquals('Y'),
    charEquals('Z'),
    char.IsDigit 
};

var result = predicates.Any(text.All);

Console.WriteLine(result);

Upvotes: 2

Ousmane D.
Ousmane D.

Reputation: 56423

You need to invoke the myPredicate function like this:

"abc".All(x => char.IsDigit(x) || myPredicate(x));

Upvotes: 6

Related Questions