mercredi 1 mars 2017

How to convert Linq expression to Reflection (To make dynamic LINQ expression)

I have created three classes. Two classes Data and IntArrayEqualityComparer are below-

public class Data
    {   
        public Dictionary<int[], List<double>> s = new Dictionary<int[], List<double>>(new IntArrayEqualityComparer());        

        public Data()
        {
        }

        public Data(Dictionary<int[], List<double>> s)
        {
            this.s = s;
        }

        public Dictionary<int[], List<double>> S
        {
            get { return s; }
            set { s = value; }
        }
    }

 public class IntArrayEqualityComparer : IEqualityComparer<int[]>
    {
        public bool Equals(int[] x, int[] y)
        {
            if (x.Length != y.Length)
            {
                return false;
            }
            for (int i = 0; i < x.Length; i++)
            {
                if (x[i] != y[i])
                {
                    return false;
                }
            }
            return true;
        }

        public int GetHashCode(int[] obj)
        {
            int result = 17;
            for (int i = 0; i < obj.Length; i++)
            {
                unchecked
                {
                    result = result * 23 + obj[i];
                }
            }
            return result;
        }
    }

A third class named Expression is created in which I need to convert LINQ expression into Reflection -

public class Expresion
    {
        public void CreateExpression()
        {
            Expression<Func<Data, List<int>>> exp1 = null;
            //Below is the LINQ expression I want to convert
            exp1 = p2 => p2.s[new int[] { 14, 5 }].Select((item, index) => new { item, index }).Select(x => x.index).ToList();

            ParameterExpression p1 = Expression.Parameter(typeof(Data), "p");
            MethodInfo mInfo = typeof(List<double>).GetMethod("get_Item");
            MethodInfo mInfo1 = typeof(Dictionary<int, List<double>>).GetMethod("get_Item");
            MethodInfo mInfo2 = typeof(Dictionary<int[], List<double>>).GetMethod("get_Item");
            MethodInfo mInfo3 = typeof(List<int[]>).GetMethod("get_Item");

            MemberExpression s1 = Expression.Property(p1, "s");
            ParameterExpression index1 = Expression.Parameter(typeof(int), "index");
            ParameterExpression item1 = Expression.Parameter(typeof(double), "item");

            //Here I want to covert the "(item, index) => new { item, index }" part from LINQ expression into Reflection
        }
    }





Aucun commentaire:

Enregistrer un commentaire