【问题标题】:How to pass an expression to a LINQ query as a parameter如何将表达式作为参数传递给 LINQ 查询
【发布时间】:2015-03-13 21:53:43
【问题描述】:

我有一些这样的陈述:

if (mediaCode.IndexOf(',') > 0) {
  entries = entries.Where(c => mediaCode.Contains(c.Mediacode));
}
else {
  entries = entries.Where(c => c.Mediacode == mediaCode);
}

然后:

if (contentType.IndexOf(',') > 0) {
    entries = entries.Where(c => contentType.Contains(c.Contenttype));
}
else {
    entries = entries.Where(c => c.Contenttype == contentType);
}

我想创建一个函数,我只传递字符串和属性, 类似于:MethodName(contentType, c.Contenttype)

这是怎么做到的?

【问题讨论】:

  • 不清楚你在问什么。您想将 Linq 查询中的表达式传递给方法吗?例如:entry.Where(conditionParameter) where conditionParameter is c=> mediaCode.Contains(value)

标签: .net reflection lambda


【解决方案1】:

使用反射(参见How to get a property value based on the name),您可以这样做:

    protected void FilterStrings(ref IEnumerable<StringStruct> entries, string contentType, string fieldName)
    {
        if (contentType.IndexOf(',') > 0)
        {
            entries = entries.Where(c => contentType.Contains(c.GetType().GetProperty(fieldName).GetValue(c, null).ToString()));
        }
        else
        {
            entries = entries.Where(c => c.GetType().GetProperty(fieldName).GetValue(c, null).ToString() == contentType);
        }
    }

你可以这样调用函数:

FilterStrings(ref entries, mediaCode, "Mediacode");

【讨论】:

  • 谢谢!这就是我要找的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-23
  • 1970-01-01
  • 2015-06-09
  • 2023-03-06
  • 2014-11-30
  • 1970-01-01
相关资源
最近更新 更多