I have a value I'm getting dynamically. This is because it exists in an abstraction method I'm using to build a query from a dot-notation representation of deeply related property.
I need to know if the value contains a particular value. This is easy enough for a string, but when the object in question is a collection I can't figure how to check. I can assume it's a List in my situation, but I don't know what type of list, so I can't achieve a property casting with something like List<int>
.
So where x
is an object
and spec
is dynamic
this is how I test for string:
return x.ToString()?.Contains(spec, StringComparison.InvariantCultureIgnoreCase) ?? false;
This successfully determines if it's a collection type, but I still can't call Contains
on it:
if (x.GetType().Namespace == "System.Collections.Generic")
{
return x.Contains(spec); //does not work
}
Also tried:
var list = (List<dynamic>)x;
var list = (List<object>)x;
But this fails in my test scenario with List<int>