使用表达式树生成LINQ查询

4

更新

感谢Marc的帮助,AlphaPagedList类现在可以在CodePlex上获得,如果有兴趣的话请前往CodePlex

原始内容

我正在尝试创建一个表达式树来返回以给定字符开头的元素。

IList<char> chars = new List<char>{'a','b'};
IQueryable<Dept>Depts.Where(x=> chars.Contains(x.DeptName[0]));

我希望这个可以用于任何IEnumerable,其中我提供一个lambda来选择属性,例如:

Depts.Alpha(x=>x.DeptName, chars);

我一直在尝试,但完全没有成功,需要帮助吗?

public static IQueryable<T> testing<T>(this IQueryable<T> queryableData, Expression<Func<T,string>> pi, IEnumerable<char> chars)
{
// Compose the expression tree that represents the parameter to the predicate.

ParameterExpression pe = Expression.Parameter(queryableData.ElementType, "x");
ConstantExpression ch = Expression.Constant(chars,typeof(IEnumerable<char>));
// ***** Where(x=>chars.Contains(x.pi[0])) *****
// pi is a string property
//Get the string property

Expression first = Expression.Constant(0);
//Get the first character of the string
Expression firstchar = Expression.ArrayIndex(pi.Body, first);
//Call "Contains" on chars with argument being right
Expression e = Expression.Call(ch, typeof(IEnumerable<char>).GetMethod("Contains", new Type[] { typeof(char) }),firstchar);


MethodCallExpression whereCallExpression = Expression.Call(
    typeof(Queryable),
    "Where",
    new Type[] { queryableData.ElementType },
    queryableData.Expression,
    Expression.Lambda<Func<T, bool>>(e, new ParameterExpression[] { pe }));
// ***** End Where *****

return (queryableData.Provider.CreateQuery<T>(whereCallExpression));
}
1个回答

2

类似这样(在重新阅读问题后编辑)-但请注意,在3.5 SP1中,Expression.Invoke不适用于EF(但在LINQ-to-SQL中可以使用):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

class Dept
{
    public string DeptName { get; set; }
}
public static class Program
{
    static void Main()
    {
        IList<char> chars = new List<char>{'a','b'};
        Dept[] depts = new[] { new Dept { DeptName = "alpha" }, new Dept { DeptName = "beta" }, new Dept { DeptName = "omega" } };
        var count = testing(depts.AsQueryable(), dept => dept.DeptName, chars).Count();
    }

    public static IQueryable<T> testing<T>(this IQueryable<T> queryableData, Expression<Func<T,string>> pi, IEnumerable<char> chars)
    {
        var arg = Expression.Parameter(typeof(T), "x");
        var prop = Expression.Invoke(pi, arg);
        Expression body = null;
        foreach(char c in chars) {
            Expression thisFilter = Expression.Call(prop, "StartsWith", null, Expression.Constant(c.ToString()));
            body = body == null ? thisFilter : Expression.OrElse(body, thisFilter);
        }
        var lambda = Expression.Lambda<Func<T, bool>>(body ?? Expression.Constant(false), arg);
        return queryableData.Where(lambda);
    }
}

非常感谢您的帮助。我正在开发一个类似于IPagedList的字母数字分页列表,这将非常有用。 - Chao

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接