gpt4 book ai didi

c# - 在动态 Lambda 表达式中获取 Count() 属性

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

我几乎得到了我需要的东西,但只有一个地方我卡住了。我需要在 Lambda 表达式中动态构建 fileCount = c.CPNDocs.Count()。下面的代码附有我用来构建动态 Lambda 表达式的注释。

var dColDefaultList = new List<String>() { "Download", "I_ID", "C_TYP", "C_LST_ACT" };       // <------- Columns I need in Lambdas Expression

ParameterExpression cParam = Expression.Parameter(typeof(CPNDBase), "c");

NewExpression newExp = Expression.New(typeof(DTDataModel));

List<MemberBinding> bindings = new List<MemberBinding>();

foreach (String sCol in dColDefaultList)
{
if (!String.Equals(sCol, "Download")) {
bindings.Add(GetMemberBinding(sCol, cParam, sCol));
}
else
{
bindings.Add(GetMemberBinding("fileCount", cParam, "CPNDocs.Count()")); // <-------need count of rows return from CPNDocs(Different Table) is a Object I recieved from Entity Relatioship
}
}

MemberInitExpression memberInitExpression = System.Linq.Expressions.Expression.MemberInit(newExp, bindings);

Expression<Func<CPNDBase, DTDataModel>> selector = (Expression<Func<CPNDBase, DTDataModel>>)BinaryExpression.Lambda(memberInitExpression, cParam);

// selector will be selector = {c => new DTDataModel() {fileCount = c.CPNDocs, I_ID = c.I_ID, C_TYP = c.C_TYP, C_LST_ACT = c.C_LST_ACT }}
// but I Need selector = {c => new DTDataModel() {fileCount = c.CPNDocs.Count(), I_ID = c.I_ID, C_TYP = c.C_TYP, C_LST_ACT = c.C_LST_ACT }}

// Question is How can I make fileCount = c.CPNDocs.Count() ?

var resultLm = finalFilteredCPNData.AsQueryable<CPNDBase>().Select(selector);

上面的方法在这里定义:

static MemberBinding GetMemberBinding(string property, ParameterExpression param,  string column)
{
MemberInfo memberInfo = typeof(DTDataModel).GetMember(property)[0];
MemberExpression memberExpression = LambdaExpression.PropertyOrField(param, column);
return System.Linq.Expressions.Expression.Bind(memberInfo, memberExpression);
}

有人知道我该怎么做吗?

最佳答案

Count() 不是属性。它是在静态类中实现的扩展方法。这个扩展方法在几个地方实现。正确的位置取决于您的类继承自什么。要找到正确的位置,您可以使用 Visual Studio 的“转到定义”功能。

例如对于 IQueryable.Count(),扩展方法由 System.Linq.Queryable 静态类实现,参见此处 → http://referencesource.microsoft.com/#System.Core/System/Linq/IQueryable.cs

因此,为了对表达式进行编码,您需要对对扩展方法的调用进行编码。

Microsoft 发布的原型(prototype)很早就展示了从字符串生成表达式树的更简单方法。介绍性文章可用,例如在 Dynamic Expressions and Queries in LINQ

我们成功地使用了自动“字符串到 linq”引擎原始源代码的修改版本,它大大简化了开发。通过检查 System.Linq.Dynamic 的源代码,您可以找到对表达式进行编码的确切方法。提到了通过 NuGet 提供的原始源代码的链接,例如在 Stack Overflow 文章中 Dynamic LINQ - Is There A .NET 4 Version?

关于c# - 在动态 Lambda 表达式中获取 Count() 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23391222/

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