为List.Any子句创建表达式 [英] Create Expression for List.Any clause

查看:111
本文介绍了为List.Any子句创建表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个类的层次结构.

Consider this hierarchy of classes.

class Event
{
    public Attendees[] AttendeesList;
}

class Attendees
{
    public ComplexProperty Property;
    public object Value;
}

class ComplexProperty
{

}

class Program
{
    static void Main(string[] args)
    {
        // There are constants.
        ComplexProperty constproperty = new ComplexProperty();
        object constValue = 5;

        // consider this linq query:
        Event evnt = new Event();

        var result = evnt.AttendeesList.Any((attnds) => attnds.Property == constproperty && attnds.Value == constValue);


        // I want to create an Expression tree for above linq query. I need something like this:
        ParameterExpression parameter = Expression.Parameter(typeof(Attendees));
        Expression left = Expression.Property(parameter, typeof(ComplexProperty).GetProperty("Property"));
        // complete this piece.......

    }
}

我想为evnt.AttendeesList.Any((attnds) => attnds.Property == constproperty && attnds.Value == constValue);创建一个Linq.Expressions.Expression 此linq查询. 如何使用Linq.Expressions查询集合看起来很相似,但是我有Any在我的linq表达式中.

I want to create a Linq.Expressions.Expression for evnt.AttendeesList.Any((attnds) => attnds.Property == constproperty && attnds.Value == constValue); this linq query. How to query collection with Linq.Expressions looks similar, but I have Any in my linq expression.

请帮助.

推荐答案

这将为您提供一个起点:

This will give you a start:

ParameterExpression parameter = Expression.Parameter(typeof(Attendees));
Expression left = Expression.Equal(Expression.Property(parameter, "Property"), Expression.Constant(constproperty));

var objType = constValue == null ? typeof(object) : constValue.GetType();
var convertLeft = Expression.Convert(Expression.Property(parameter, "Value"), objType);
var convertRight = Expression.Convert(Expression.Constant(constValue), objType);
Expression right = Expression.Equal(convertLeft, convertRight);
Expression joined = Expression.And(left, right);

var anyMethod = typeof(Queryable).GetMethods().Where(m => m.Name=="Any" && m.GetParameters().Count() == 2).First().MakeGenericMethod(typeof(Attendees));
var call = Expression.Call(anyMethod, Expression.Constant(evnt.AttendeesList, typeof(IQueryable<Attendees>)), Expression.Lambda(joined, parameter));

为了便于使用,我将Value更改为int类型.如果要将其保留为对象,则需要在right表达式中添加一个Expression.Convert()调用.

I changed Value to type int for ease of use. If you want to keep it as an object, you will need to add a Expression.Convert() call in the right Expression.

这篇关于为List.Any子句创建表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆