mercredi 7 décembre 2016

How to work with Generic type members in extension method?

I started this extension method for fun, but now I find myself stuck into it,

Actually I want to create an extension method to extend LINQ, the method will look like this:

books.In(b => b.Id, 1,2,3,4,5);

It will return books with Id range in the second params[] ,

It also could be done like this:

books.In(b => b.Title, "t1","t2","t3","t4","t5");

What I come up with is this method (I just knew about expression tree today!):

 public static List<TEntity> In<TEntity, TMember>(this List<TEntity> list,
            Expression<Func<TEntity, TMember>> identifier, params TMember[] keys)
        {
            Type t = typeof(TEntity); //How to use reflection here?

            List<TEntity> myList = list.Where(m => keys.Contains(m.));
            return myList;
        }

my problem is how to access the generic class members: i.e. m.Id or m.Title from the identifier expression? Can I use reflection to make this happen?





Aucun commentaire:

Enregistrer un commentaire