I need to create functionality that would allow users to filter entities using literal queries (i.e. age gt 20 and name eq 'john'
). Is there a provided functionality to do this in C#/Asp.Net MVC or do I have to parse this query by myself?
我需要创建功能,允许用户使用文字查询过滤实体(例如,年龄为20岁,名字为eq 'john')。在c# /Asp中是否提供了这样的功能。还是我必须自己解析这个查询?
I found that OData implies having exactly such functionality (OData Filter Expressions MSDN). However, I'm not familiar with it so I don't know how to implement such behavior in my project.
我发现OData意味着具有完全这样的功能(OData Filter表达式MSDN)。但是,我不熟悉它,所以我不知道如何在我的项目中实现这种行为。
I need something like this:
我需要这样的东西:
var list = new List<Person>
{
new Person { Name = "John", Age = 30 },
new Person { Name = "Hanna", Age = 25 },
new Person { Name = "John", Age = 15 }
};
string query = "age gt 20 and name eq /'John/'";
IEnumerable<Person> result = list.FilterByExpression(query);
// returns list with John aged 30
Any advice would be appreciated.
如有任何建议,我们将不胜感激。
1 个解决方案
#1
2
There is a package on Nuget called Linq2Rest
, which contains an extension method for IEnumerable
called Filter
. You can pass the string of the filter you need to make the filter happen. Internally, it will be converted into a Expression Tree
and will be used with the ienumerable extension methods existent.
在Nuget上有一个名为Linq2Rest的包,它包含一个名为Filter的IEnumerable的扩展方法。您可以传递您需要的过滤器的字符串以使过滤器发生。在内部,它将被转换为表达式树,并将与现有的ienumerable扩展方法一起使用。
For sample:
示例:
var filteredSource = source.Filter(Request.Params);
See this article Creating a .Net queryable client for ASP.Net Web API oData services
about how to deal with this type of problem using libraries JSON.Net
and Linq2Rest
to solve this problem.
参见本文为ASP创建. net可查询客户端。Net Web API oData服务,关于如何使用库JSON处理此类问题。Net和Linq2Rest解决这个问题。
#1
2
There is a package on Nuget called Linq2Rest
, which contains an extension method for IEnumerable
called Filter
. You can pass the string of the filter you need to make the filter happen. Internally, it will be converted into a Expression Tree
and will be used with the ienumerable extension methods existent.
在Nuget上有一个名为Linq2Rest的包,它包含一个名为Filter的IEnumerable的扩展方法。您可以传递您需要的过滤器的字符串以使过滤器发生。在内部,它将被转换为表达式树,并将与现有的ienumerable扩展方法一起使用。
For sample:
示例:
var filteredSource = source.Filter(Request.Params);
See this article Creating a .Net queryable client for ASP.Net Web API oData services
about how to deal with this type of problem using libraries JSON.Net
and Linq2Rest
to solve this problem.
参见本文为ASP创建. net可查询客户端。Net Web API oData服务,关于如何使用库JSON处理此类问题。Net和Linq2Rest解决这个问题。