0

I have a problem trying to cast a Predicate<T> to Func<T, bool>. I have a method that accepts a object[] variable as argument:

protected abstract Predicate<TResults> PredicateFind(object[] values);

It works perfectly for List.Find:

protected TResults Find(params object[] values) => Resultados.Find(PredicateFind(values));

but trying to use it with List.Any:

protected TResults Any(params object[] values) => Resultados.Any(r => new Func<TResults, bool>(x => (bool)PredicateFind(values) == true));

gives:

CS0030: Cannot convert type 'System.Predicate<TResults>' to 'bool'

Trying to change it to

protected TResults Any(params object[] values) => Resultados.Any(PredicateFind(values));

gives:

CS1503: Argument 2: cannot convert from 'System.Predicate<TResults>' to 'System.Function<TResults, bool>'

And changing it to

protected TResults Any(params object[] values) => Resultados.Any(new Func<TResults, bool>(PredicateFind(values)));

gives

CS0029: Cannot implicitly convert type 'bool' to 'TResults'

How should I call Predicate(object[] values) to be able to use it with Any?

Thank you


EDIT

Finally the problem was in

protected TResults Any(params object[] values) => Resultados.Any(PredicateFind(values));

First I had to change the return type to bool

protected bool Any(params object[] values) => Resultados.Any(PredicateFind(values));

and second I had to change the argument to r => PredicateFind(values).Invoke(r)

protected bool Any(params object[] values) => Resultados.Any(r => PredicateFind(values).Invoke(r));

Now it's fixed.

Thank you all.

elgato
  • 506
  • 1
  • 5
  • 20
  • 1
    The [Any](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.any?view=net-5.0#System_Linq_Enumerable_Any__1_System_Collections_Generic_IEnumerable___0__System_Func___0_System_Boolean__) function iterates over all elements in the list and returns whether at least one of them matches a condition. Are you sure it's what you're trying to do? Your `PredicateFind` doesn't consider the list elements at all. – Bip901 Dec 20 '20 at 17:13
  • Can you tell us what you are actually trying to do with the Any method? I'm not quite sure what you are trying to accomplish. Any doesn't return elements, it returns true or false. – Todd Skelton Dec 20 '20 at 17:20
  • I want to check if there is any TResults that satisfies a condition. The condition depends on the class that is implementing `protected abstract Predicate PredicateFind(object[] values);`, but usually consists of checking a property of TResults contains or is equal to a value – elgato Dec 20 '20 at 18:38

0 Answers0