如何将表达式作为参数传递给LINQ查询

时间:2015-03-13 21:53:44

标签: .net reflection lambda

我有几个这样的陈述:

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)

怎么可以这样做?

1 个答案:

答案 0 :(得分:0)

使用反射(参见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");