gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:23:00 25 4
gpt4 key购买 nike

我正在使用 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();

关于c# - 编写基本的表达式生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29388178/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com