Linq to Object, reflexion et expression
Bonjour, je suis coincé dans un logiciel, donc je vous ai remis un équivalent dans un petit programme console qui produit la même erreur.
La requete en commentaire produit le résultat désiré, j'essaye tout simplement de la refaire sous une autre forme
Voici le code :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;
using System.Collections;
using System.Reflection;
using System;
namespace ConsoleApplication1
{
class Program
{
class Personne
{
public string Nom { get; set; }
public string Prenom { get; set; }
}
static void Main(string[] args)
{
List<Personne> Liste = new List<Personne>();
Liste.Add(new Personne() { Nom = "toto", Prenom = "JP" });
Liste.Add(new Personne() { Nom = "Lagaffe", Prenom = "Gaston" });
IEnumerable RequeteLinq;
PropertyInfo propriete = typeof(Personne).GetProperty("Nom");
/*
RequeteLinq = Liste.Where(p => propriete.GetValue(p, new object[0]).ToString().StartsWith("toto"));
*/
var p = Expression.Parameter(typeof(object), "p");
Expression G = Expression.Call(
Expression.Constant(propriete),
typeof(System.Reflection.PropertyInfo).GetMethod("GetValue", new System.Type[] { typeof(object), typeof(object[]) }),
Expression.Constant(p),
Expression.Constant(new object[0]));
G = Expression.Call(G, typeof(object).GetMethod("ToString", new Type[0]));
G = Expression.Call(
G,
typeof(string).GetMethod("StartsWith", new[] { typeof(string) }),
Expression.Constant("toto"));
var lambda = Expression.Lambda<Func<object, bool>>(G, p);
var predicat = lambda.Compile();
RequeteLinq = Liste.Where(predicat);
foreach (object req in RequeteLinq)
Console.WriteLine(req);
Console.ReadLine();
}
}
} |
je sais qu'on peut avoir le résultat attendu simplement avec du linq to object, sans expression et reflexion, mais j'en ai besoin pour mon logiciel :mouarf:
Donc l'erreur est sur mon foreach, quelqu'un sait pourquoi ?
merci,
Zunk