Skip to main content
 首页 » 编程设计

c#之编写基本的表达式生成器

2024年02月06日12lautakyan007

我正在使用 Linq-to-Entities,一个查询需要动态加载一个属性。查询如下所示:

var found = Context.IntegrateViews.GroupBy(x => x.TypeOfBed) 
                   .Select(type => new TypeCounts 
                            { Name = type.Key, Count = type.Count() }).ToList(); 

运行 Group By 子句的属性是 TypeOfBed。现在我想在不同的属性上运行此查询,例如,下次我想运行它时,假设是 x.TypeOfChair 等等。为此,我需要在其中动态设置此属性。

我正在尝试编写一个像这样的表达式构建器。

public Expression<Func<LookupFilterItem>> PropertyLambda(string propertyName) 
{ 
    var param = Expression.Parameter(typeof(LookupFilterItem), "lookupItem"); 
    //type of x in above example is LookupFilterItem 
    var propertyExpression = Expression.Property(param, propertyName); 
 
    var returnExpr = Expression.Lambda<Func<LookupFilterItem>>(propertyExpression); 
    return returnExpr; 
    //If I Pass string "TypeOfBed" to this method, I am expecting it to return something like 
    // lookupItem => lookupItem.TypeOfBed 
} 

我打算这样使用它:

var found = Context.IntegrateViews.GroupBy(PropertyLambda("TypeOfBed")) 
                   .Select(type => new TypeCounts 
                            { Name = type.Key, Count = type.Count() }).ToList(); 

但这是行不通的,我收到一个编译时错误:

error CS0411: The type arguments for method 'System.Linq.Queryable.GroupBy(System.Linq.IQueryable, System.Linq.Expressions.Expression>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

我在这里做错了什么?

请您参考如下方法:

这似乎是一个语法问题。试试这个:

public Expression<Func<LookupFilterItem, string>> PropertyLambda(string propertyName) 
    { 
        var param = Expression.Parameter(typeof(LookupFilterItem), "lookupItem"); 
        var propertyExpression = Expression.Property(param, propertyName); 
        var returnExpr = Expression.Lambda<Func<LookupFilterItem, string>>(propertyExpression, param); 
        return returnExpr; 
    } 

以及用法:

var found = Context.IntegrateViews.GroupBy(PropertyLambda("TypeOfBed").Compile()) 
               .Select(type => new TypeCounts 
                        { Name = type.Key, Count = type.Count() }).ToList();