pattern genericrepository generic framework c# .net-3.5 lambda

c# - genericrepository - ¿Cómo convertir Func<T, bool> a Predicate<T>?



generic base repository c# (4)

Fácil:

Func<string,bool> func = x => x.Length > 5; Predicate<string> predicate = new Predicate<string>(func);

Básicamente, puede crear una nueva instancia de delegado con cualquier instancia existente compatible . Esto también apoya la varianza (co- y contra-):

Action<object> actOnObject = x => Console.WriteLine(x); Action<string> actOnString = new Action<string>(actOnObject); Func<string> returnsString = () => "hi"; Func<object> returnsObject = new Func<object>(returnsString);

Si quieres hacerlo genérico:

static Predicate<T> ConvertToPredicate<T>(Func<T, bool> func) { return new Predicate<T>(func); }

Sí, he visto this pero no pude encontrar la respuesta a mi pregunta específica.

Dada una lambda testLambda que toma T y devuelve un booleano (puedo hacer que sea Predicado o Func, eso depende de mí)

Necesito poder usar tanto List.FindIndex (testLambda) (toma un Predicado) como List.Where (testLambda) (toma una función).

¿Alguna idea de cómo hacer ambas cosas?


Llego un poco tarde al juego, pero me gustan los métodos de extensión:

public static class FuncHelper { public static Predicate<T> ToPredicate<T>(this Func<T,bool> f) { return x => f(x); } }

Entonces puedes usarlo como:

List<int> list = new List<int> { 1, 3, 4, 5, 7, 9 }; Func<int, bool> isEvenFunc = x => x % 2 == 0; var index = list.FindIndex(isEvenFunc.ToPredicate());

Hmm, ahora veo el método de extensión FindIndex. Esta es una respuesta un poco más general, supongo. No es realmente muy diferente de ConvertToPredicate tampoco.


Suena como un caso para

static class ListExtensions { public static int FindIndex<T>(this List<T> list, Func<T, bool> f) { return list.FindIndex(x => f(x)); } } // ... Func<string, bool> f = x=>Something(x); MyList.FindIndex(f); // ...

Me encanta C # 3 ...


Tengo esto:

Func<object, bool> testLambda = x=>true; int idx = myList.FindIndex(x => testLambda(x));

Funciona, pero ick.