Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter entities using queries in C#?

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?

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.

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.

like image 507
Ivan Yurchenko Avatar asked Oct 29 '22 01:10

Ivan Yurchenko


1 Answers

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.

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.

like image 167
Felipe Oriani Avatar answered Nov 09 '22 23:11

Felipe Oriani