Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I obtain a set of Key/Value pairs for each filter specified in an OData query using C#?

Tags:

c#

asp.net

odata

I have an ASP.Net WebAPI service that accepts OData queries. One of my controller methods accepts an ODataQueryOptions instance and applies it to an IQueryable instance. So far so good. Everything is working as planned.

Now, I have a specific need to obtain one of the key/value pairs from the OData query. For example, if I have two filters specified (someproperty eq 123 and otherproperty eq 456), how can I obtain one of the key/value pairs from the raw filter? I've looked at some of the ODataUriParser documentation, but it is really complicated and seems overkill. Isn't there an easier way to obtain simple key/value pairs, like I would from a normal QueryString?

EDIT: I've since put in some manual string parsing to accomplish what I needed, but that's obviously not ideal. Therefore, I'm putting up a bounty on this question. Hopefully someone has a simple solution to this!

like image 970
Kilhoffer Avatar asked Dec 06 '25 19:12

Kilhoffer


1 Answers

There is an easy approach using regex where you convert your Odata query filter into key Value pair , regex 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 something like,

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

Which gives you output like,

someproperty:123,otherproperty:456

Then convert that string into dictionary of your KeyValue parameter or however you want to consume it

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

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

    }
like image 146
gunvant.k Avatar answered Dec 08 '25 09:12

gunvant.k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!