0

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>

Randy Hall
  • 7,716
  • 16
  • 73
  • 151
  • You might want to look at https://stackoverflow.com/questions/22173762/check-if-two-lists-are-equal – Progman Nov 06 '22 at 19:01
  • _I need to know if the value contains another value._ What does it mean? Do you wanna know what property/field is contained or any value in a propery/field? – Soner from The Ottoman Empire Nov 06 '22 at 19:08
  • @SonerfromTheOttomanEmpire updated. Basically `List.Contains()` functionality on an anonymous object. – Randy Hall Nov 06 '22 at 19:18
  • @RandyHall convert the object to json string all-inclusive. Then, use string's contains method, which I would do. – Soner from The Ottoman Empire Nov 06 '22 at 19:21
  • What you're trying to do seems very obscure and I think the question would benefit from a more complete and real example. Other than that, since you're basically duck-typing anyway with little regard to code sanity, why don't you just look for a `Contains` method via reflection and just invoke that? – dialer Nov 06 '22 at 19:26
  • Definitely you can do `dynamic list = x;`, although I don't recommend it. – yueyinqiu Nov 07 '22 at 02:48

0 Answers0