通用类和过滤

时间:2018-06-03 14:32:31

标签: c# linq generics

我有一个通用类:

public class DataProvider<T> where T : class
{
    private readonly IService<T> _service;
    public DataProvider(IService<T> service) => _service = service;

    public IQueryable<T> List(params string[] includes) => _service.List(includes);
}

现在我想基于任何查询字符串参数过滤结果。 比方说,我想返回包含单词&#34; Special&#34;但对于特定的领域。也许查询字符串看起来像这样:

?标题=特殊

我想使用linq来过滤结果,但我不确定是否可行。 我将列表方法更改为:

public IQueryable<T> List(HttpRequestMessage request, params string[] includes)
{
    var queryString = request.GetQueryNameValuePairs();
    var models = _service.List(includes);
    // TODO: Do a contains linq query
}

可以这样查找吗?或者我必须将我的Generic类型更改为类:

public class DataProvider<T> where T : Availability
{
    private readonly IService<T> _service;
    public DataProvider(IService<T> service) => _service = service;

    public IQueryable<T> List(HttpRequestMessage request, params string[] includes)
    {
        var queryString = request.GetQueryNameValuePairs();
        var models = _service.List(includes);
        // TODO: Do a contains linq query
    }
}

即便如此,如何动态查找属性? 我有这样的事情:

foreach (var item in queryString)
    models = models.Where(m => m.GetType().GetProperty(item.Key).GetValue(m).ToString().Contains(item.Value));

任何人都知道如何做到这一点?

1 个答案:

答案 0 :(得分:0)

使用Dynamic Linq,我能够做到这一点:

public class DataProvider<T> where T : class
{
    private readonly IService<T> _service;
    public DataProvider(IService<T> service) => _service = service;

    public IQueryable<T> List(HttpRequestMessage request)
    {
        var queryString = request.GetQueryNameValuePairs();
        var models = _service.List();
        foreach (var item in queryString)
        {
            var query = $"{ item.Key }.ToString().Contains(\"{ item.Value }\")";
            models = models.Where(query);
        }
        return models;
    }
}

这解决了我的问题