如何将谓词表达式分解为查询?

Shl*_*emi 5 c# linq lambda

我有以下类Person,使用自定义Where方法:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public string Where(Expression<Func<Person, bool>> predicate)
    {
        return String.Empty;
    }
}
Run Code Online (Sandbox Code Playgroud)

如何Expression以可枚举的方式检索参数名称和值?

Person p = new Person();
p.Where(i => i.Name == "Shlomi" && i.Age == 26);
Run Code Online (Sandbox Code Playgroud)

用于根据表达式的名称和值构建带有参数的字符串查询.

// Eventually I will convert the above into the following:
string Query = "select * from person where name = @Name AND Age = @Age";

SqlParameter[] param = new SqlParameter[] { 
    new SqlParameter("@Name","Shlomi"),
    new SqlParameter("@Age","26")
};
Run Code Online (Sandbox Code Playgroud)

use*_*116 9

我当然认为你应该遵循StriplingWarrior的建议并使用LINQ to Entities或LINQ to SQL,但为了重新发明轮子(糟糕的是),我将建立我的先前答案.

// Start with a method that takes a predicate and retrieves the property names
static IEnumerable<string> GetColumnNames<T>(Expression<Func<T,bool>> predicate)
{
    // Use Expression.Body to gather the necessary details
    var members = GetMemberExpressions(predicate.Body);
    if (!members.Any())
    {
        throw new ArgumentException(
            "Not reducible to a Member Access", 
            "predicate");
    }

    return members.Select(m => m.Member.Name);
}
Run Code Online (Sandbox Code Playgroud)

现在,您需要遍历表达式树,访问每个候选表达式,并确定它是否包含a MemberExpression.GetMemberExpressions下面的方法将遍历表达式树并检索其中的每个MemberExpressions:

static IEnumerable<MemberExpression> GetMemberExpressions(Expression body)
{
    // A Queue preserves left to right reading order of expressions in the tree
    var candidates = new Queue<Expression>(new[] { body });
    while (candidates.Count > 0)
    {
        var expr = candidates.Dequeue();
        if (expr is MemberExpression)
        {
            yield return ((MemberExpression)expr);
        }
        else if (expr is UnaryExpression)
        {
            candidates.Enqueue(((UnaryExpression)expr).Operand);
        }
        else if (expr is BinaryExpression)
        {
            var binary = expr as BinaryExpression;
            candidates.Enqueue(binary.Left);
            candidates.Enqueue(binary.Right);
        }
        else if (expr is MethodCallExpression)
        {
            var method = expr as MethodCallExpression;
            foreach (var argument in method.Arguments)
            {
                candidates.Enqueue(argument);
            }
        }
        else if (expr is LambdaExpression)
        {
            candidates.Enqueue(((LambdaExpression)expr).Body);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 难道我们Stackoverflowers不仅仅是为了惩罚吗?+1 (2认同)