vendredi 22 janvier 2016

Use LINQ aggregator dinamically

I'm trying to create a method that uses Linq aggregator functions, like Sum, Average and Count. I have the following code:

private double AgreggateDynamic<T>(IEnumerable<T> list, string propertyName, string func)
{       
    //Already tried this
    //IEnumerable<T> listEnum = list.ToList();     
    Type enumerableType = typeof(Enumerable);

    MethodInfo sumMethod = typeof(Enumerable).GetMethods().First(
        m => m.Name == func
            && m.IsGenericMethod);

    MethodInfo generic = sumMethod.MakeGenericMethod(enumerableType);
    Func<T, double> expression = x => Convert.ToDouble(x.GetType().GetProperty(propertyName).GetValue(x, null));
    object[] parametersArray = new object[] { list, expression };

    return Convert.ToDouble(generic.Invoke(null, parametersArray));
}

AgreggateDynamic(list, "FooValue", "Sum");

When I run this code, it throws an error on this line "return Convert.ToDouble(generic.Invoke(null, parametersArray));".

Error:

Object of type 'Manager.Business.Tests.Foo[]'cannot be converted to object of type 'System.Collections.Generic.IEnumerable`1[System.Linq.Enumerable]'.

What can I do?





Aucun commentaire:

Enregistrer un commentaire