How can I get a set of key / value pairs for each filter specified in an OData query using C #?

I have an ASP.Net WebAPI service that accepts OData requests. One of my controller methods takes an instance ODataQueryOptions

and applies it to the instance IQueryable

. So far, so good. Everything works as planned.

Now I have a specific need to get one of the key / value pairs from an OData request. For example, if I have two filters specified (someproperty eq 123 and otherproperty eq 456)

, how can I get one of the key / value pairs from the raw filter? I've looked at some of the ODataUriParser documentation, but it's really complicated and seems overkill. Isn't there an easier way to get simple key / value pairs like from a regular QueryString?

EDIT: I've since gone through a few manual lines to accomplish what I needed, but this is obviously not ideal. So I raise a bounty on this question. Hope someone has a simple solution!

+3


source to share


1 answer


There is a simple approach using regex where you convert your Odata query filter to the Value, regex key pair found from this answer Here

string strRegex = @"(?<Filter>" + 
"\n" + @"     (?<Resource>.+?)\s+" + 
"\n" + @"     (?<Operator>eq|ne|gt|ge|lt|le|add|sub|mul|div|mod)\s+" + 
"\n" + @"     '?(?<Value>.+?)'?" + 
"\n" + @")" + 
"\n" + @"(?:" + 
"\n" + @"    \s*$" + 
"\n" + @"   |\s+(?:or|and|not)\s+" + 
"\n" + @")" + 
"\n";

      

your replacement string is like

string strReplace = @"${Resource}:${Value}," 

      



Which gives you an output like

someproperty:123,otherproperty:456

      

Then convert that string to the dictionary of your KeyValue parameter or still want to use it

public Dictionary<String, String> getKeyValue(String input)
    {

           return input.Split(',').ToDictionary(kv => kv.Split(':').First(), kv => kv.Split(':').Last());

    }

      

+1


source







All Articles