5

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.

1 Answer 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.

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.