Thursday, March 31, 2011

How to apply a function to an IQueryable instance?

I've begun playing a bit with implementing an IQueryable<T> datatype to query using LINQ. For example I've made a couple of functions like this (It is just a temporary detail that the extension method is not for the specific IQueryable implementation):

public static IQueryable<T> Pow<T>(this IQueryable<T> values, T pow)
{
    var e = BinaryExpression.Power(values.Expression, ConstantExpression.Constant(pow));

    return values.Provider.CreateQuery<T>(e);
}

Then I figured it would be useful to apply a function to each element in the IQueryable object but I can't quite figure out how to construct the proper expression. The method signature could look like this:

public static IQueryable<T> Map<T>(this IQueryable<T> values, Expression<Func<T,T>> map)
{
    Expression e = ...

    return values.Provider.CreateQuery<T>(e);
}

How should I complete this method body?

From stackoverflow
  • You are looking for the .Select() method

  • It seems to me that you are inventing Select. I don't see the difference between your Map and what Select already does. It returns an IQueryable<U> based on an expression and an initial IQueryable<T>.

    For something like Reduce/Fold, see the Queryable.Aggregate function.

    Morten Christiansen : It appears that you are right. I suppose I should just follow a couple of tutorials instead of implementing random stuff ;)

0 comments:

Post a Comment