jeudi 4 octobre 2018

How can I filter with reflection in a list? c#

I want to filter my result object but I don't know the type of object. How can I do this with reflection? I know the name of the property I'm filtering.

public class result<T> where T : class
{
    private T sResult;

    public T Result
    {
        get { return sResult; }
        set {

           /* var ty = value.GetType().GetGenericArguments().FirstOrDefault();

           var aa =  Activator.CreateInstance(ty);*/

            /* T is List<T> is giving error */
            var param = Expression.Parameter(typeof(T));
            var condition =
                Expression.Lambda<Func<T, bool>>(
                    Expression.Equal(
                        Expression.Property(param, "Id"),
                        Expression.Constant(1, typeof(int))
                    ),
                    param
                ).Compile(); // for LINQ to SQl/Entities skip Compile() call

            var exceptList =((value)as List<T>).Where(condition).ToList();
            var newListe = ((value) as List<T>).Except(item);

            sResult= newListe ;
        }
    }
}

Smaple Use:

public class personnel
        {
            public int Id { get; set; }
            public string Adi { get; set; }
        }
var list = new List<personel> { new personel { Id = 1, Adi="Jhon" }, new personel { Id = 2, Adi = "Jake" } };
                result<List<personnel>> result= new result<List<personnel>>();
                result.Result= list ;
                var newListCount = result.Sonuc.Count(); // Must be 1





Aucun commentaire:

Enregistrer un commentaire