mercredi 9 septembre 2020

How to perform foreach on object with is list of enum dynamically

I have an enum like

enum MyEnum
{
    e1 = 0, 
    e2 = 1,
    e3 = 2,
}

and a few other enums. I deserialize json to object, and one of object member is list of MyEnum or a list of OtherEnum.

I need to perform foreach on the list.

I checked if this member is a list and try to perform foreach on this list like this:

var itemValue = item.GetValue(json);
    
if (IsList(itemValue))
{
   foreach (var listItem in (IEnumerable<dynamic>)itemValue)
   {
      //do something
   }
}

What I have tried:

  1. Cast to list of: dynamic, object, string or int did not work. It always required to cast to IList<MyEnum>

  2. Get type of element from list by using

    Type type = itemValue.GetType().GetGenericArguments()[0];
    

    but compiler displays an error

    type is var but is used like Type

I know that some workaround is using string instead of enum, but I want to avoid it.

Thanks in advance.





Aucun commentaire:

Enregistrer un commentaire