【问题标题】:Reflected property(dynamic property) inside Linq lambdaLinq lambda 中的反射属性(动态属性)
【发布时间】:2018-02-11 11:46:27
【问题描述】:

如何将x.Demographic.AgeRange 替换为任何其他字段? 例如

var field_to_check  = "Country";
x.Demographic.ReflectedProperty(field_to_check)=="USA"



var field_to_check  = "AgeRnage";
x.Demographic.ReflectedProperty(field_to_check)=="20-30"

我尝试使用 rereflected 属性。但无法成功。

  Favourability = db.Questions
                    .OrderByDescending(x => x.Responces.Count(y => y.Responseval == Constants.options.Agree || y.Responseval == Constants.options.Tend_to_Agree))
                    .Select(z => new
                    {

                        z.QuestionTitle,
                        Count = z.Responces.Where(x =>
                                x.Demographic.AgeRange == repval &&
                                (x.Responseval == Constants.options.Agree || x.Responseval == Constants.options.Tend_to_Agree)
                        )
                        .Count()
                    })
                    .Select(z => new
                    {
                        z.QuestionTitle,
                        z.Count,
                        Perc = ((z.Count / totresponcecount) * 100)
                    }
                    )
                    .ToList();

这样我就可以只编写一个 linq 语句作为动态过滤,而不是为所有必需属性编写 switch 语句。

【问题讨论】:

  • “与任何其他领域”是什么意思?你想达到什么目的?目前这感觉有点像 XY 问题。
  • @ Jon Skeet,类似 var feild = Country x.Demographic.feild == repval 而不是
  • 抱歉,这仍然真的不清楚。请编辑您的问题以使其更清晰 - 并且最好也简化代码,因为您提供了相当多的代码,我怀疑其中大部分是无关紧要的。 minimal reproducible example 是理想的选择。

标签: c# .net linq expression-trees


【解决方案1】:

您可以从多个不同的表达式树中构建表达式树。使用 LinqKit,并编写:

Expression<Func<Demography, string>> fieldSpec = d => d.AgeRange;

然后在你的表达中:

var exp =  db.Questions.AsExpadable() ... fieldSpec.Expand(x.Demographic) == repval ...

现在您需要做的就是动态构建 fieldSpec,这对您来说是一个练习 :)

【讨论】:

    猜你喜欢
    • 2013-10-08
    • 2013-03-14
    • 2020-12-14
    • 2014-09-20
    • 1970-01-01
    • 2014-02-12
    • 2012-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多