Using LINQ Dynamic Query Library with dictionary <string, object> and .AsQueryable ()
In one of my previous questions about using dynamically constructed strings (where clauses are) and using them in LINQ, I went to LINQ Dynamic Query Library Dynamic LINQ .
The first problem was that it only applies to IQueryable, however it can be overcome with the .AsQueryable () extension method for any IEnumerable.
The problem I ran into was that Dynamic LINQ is looking for the "CustomerID" property (or everything that was passed to the line predicate for dynamic linq) in my dictionary. Which, obviously, will not work, since the dictionary contains only keys and values.
Therefore, thinking that I am smart, I created a class that extends : Dictionary<string, object> , ICustomTypeDescriptor`.
This allowed me to override the GetProperties() . It's great. Now I can iterate over the dictionary keys and add them to the PropertyDescriptorCollection , which is returned.
But then I ran into another problem. Throughout the Dynamic LINQ library, they work with an "Expression instance" that contains only Type. But for my CustomTypeDescriptor solution to work, I need an actual Type instance before I can apply TypeDescriptor.GetProperties(instance, false) .
So, let's move on to the real question. Given all the above information, how can I apply the custom where clause in the format of the string "CustomerID = 1234 AND Quantity> = 10000" to the LINQ query if the data is stored in dictionaries with key value pairs.
My current solution converts the data to a DataTable and uses the .Select(query) method. What works, but I'm interested in finding other solutions. Especially for benchmarking purposes.
Any ideas?
Firstly - if you use such a dictionary in this way, then you do not use it as a dictionary - you tried:
var qry = myDictionary.Values.AsQueryable().Where(sQuery); (note that if you use object , you probably want Cast<Customer> or OfType<Customer> )
Otherwise:
T in IEnumerable<T> (and therefore also for IQueryable<T> after calling the extension method AsQueryable() ) for Dictionary<TKey,TValue> there is KeyValuePair<TKey,TValue> - so you should be able to use Where("Value.CustomerID == 12345") or something similar.