How to filter objects using queries in C #?

I need to create functionality that will allow users to filter objects using literals (i.e. age gt 20 and name eq 'john' ). Is there a provided function for this in C # / Asp.Net MVC or do I need to parse this request myself?

I found that OData implies the presence of such functionality ( OData Filter Expressions MSDN ). However, I am not familiar with this, so I do not know how to implement this behavior in my project.

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.

+5
source share
1 answer

There is a package on Nuget called Linq2Rest that contains an extension method for IEnumerable called Filter . You can pass the filter string needed to create the filter. Inside, it will be converted to an Expression Tree and will be used with existing ienumerable extension methods.

For sample:

 var filteredSource = source.Filter(Request.Params); 

See Creating a .Net queryable client for ASP.Net Web API oData services on how to deal with this type of problem using the JSON.Net and Linq2Rest to solve this problem.

+2
source

Source: https://habr.com/ru/post/1272311/


All Articles