I am using dynamic Linq for generic search. I have list of Ids:
List<int> idList = new List<int> { 1, 5, 6};
In plain Linq, I would write:
q = q.Where(a => idList.Contains(a.MyId));
But now I have to use System.Linq.Dynamic
because I don't know in advance name of the column.
string someId = "CustomId";
q = q.Where("@0"+ ".Contains(" + someId + ")", idList.ToArray());
But this gives error:
"No applicable method 'Contains' exists in type 'Int32'"
How can I achieve this?
Is there some extension library that implements Contains
for dynamic
Linq or some other way.
You could write something like this that builds your query function dynamically:
Then, it could be used like this:
Of course, you could also just provide your own
Where
extension method that does all that at once:If you look at the source of Dynamic LINQ then you can see that parsing in many cases depends on variable
predefinedTypes
.In your case you need change this variable like this
after that next code will be work
@Felipe Oriani in his 90% answer used the
string.Contains
method and theyourId
single value, but asked was:q = q.Where(a => idList.Contains(a.MyId));
which is member (property) access to the
a
.So here is the final tested extension method:
The example:
You could use the
expressions
to do this dynamic query, try something like this, for sample:import these namespaces:
And try this:
Obs: make sure your property has a method called
contains
.Another way to skin this cat would be to convert the contains to ORs.
someArray.Constains(someField) is equivalent to:
someField == someArray[0] or someField == someArray[1] and so on.
It's not ideal but if the array is small it could work.