类型'布尔'期望与动态Linq

本文关键字:动态 Linq 布尔 类型 期望 | 更新日期: 2023-09-27 17:52:54

我在ASP中使用了Kendo Grid。我创建了一个自定义的服务器端过滤器,如下所示:

public string CreateString(IEnumerable<IFilterDescriptor> filters, string defaultFilter)
{
    StringBuilder builder = new StringBuilder();
    if (filters == null || filters.Count() == 0)
    {
        _filterstring = defaultFilter;
        return _filterstring;
    }
    if (filters.Any())
    {
        foreach (Kendo.Mvc.FilterDescriptor filter in filters)
        {
            string template = Templates[filter.Operator.ToString().ToLower()];
            builder.AppendFormat(template, filter.Member, filter.Value);
        }
    }
    _filterstring = builder.ToString();
    return _filterstring;
}
private static readonly IDictionary<string, string> Templates = new Dictionary<string, string>
{
    { "eq", "{0} = '{1}'" },
    { "neq", "{0} <> '{1}'" },
    { "lt", "{0} < '{1}'" },
    { "lte", "{0} <= '{1}'" },
    { "gt", "{0} > '{1}'" },
    { "gte", "{0} >= '{1}'" },
    { "startswith", "{0} like '{1}*'" },
    { "endswith", "{0} like '*{1}'" },
    { "contains", "{0} like '*{1}*'" },
    { "doesnotcontain", "{0} not like '*{1}*'" }
};

返回如下的string:

Title like '*a*'

我使用Linq.Dynamic,我过滤数据集如下:

var articleCategories = _articleCategories.AsQueryable();
    if (!string.IsNullOrEmpty(filter))
        articleCategories = articleCategories.Where(filter).ToList();

但是它返回这个错误:

期望类型为"布尔"的表达式。

类型'布尔'期望与动态Linq

我不是真的很好,但你可能缺乏一个逻辑and之间的过滤器?我在你的代码中添加了一个,但我不是很擅长这个。告诉我它是否有效。

if (filters == null || filters.Count() == 0)
{
    _filterstring = defaultFilter;
    return _filterstring;
}
if (filters.Any())
{
    string template = Templates[filters[0].Operator.ToString().ToLower()];
    builder.AppendFormat(template, filter.Member, filter.Value);
    if (filters.Count() > 1) {
        foreach (Kendo.Mvc.FilterDescriptor filter in filters.Skip(1))
        {
            template = " && " + Templates[filter.Operator.ToString().ToLower()];
            builder.AppendFormat(template, filter.Member, filter.Value);
        }
    }
}