How to iterate through a list of classes and use them as generic types?

Viewed 70

I have a list 30 model classes and I have to do the following actions for each class:

private static IEdmModel GetEdmModel(IServiceProvider serviceProvider)
{
   var odataBuilder = new ODataConventionModelBuilder(serviceProvider);

odataBuilder
 .EntitySet<AnswerCondition>("AnswerConditions")
 .EntityType
 .Select()
 .Expand()
 .OrderBy()
 .Filter()
 .Count();

Now I want to have a list of keys-values and do this action inside a for loop:

var list = new List<KeyValuePair<string, Type>>() {
          new KeyValuePair<string, Type>("ActionTypes", typeof(ActionType)),
          new KeyValuePair<string, Type>("AnswerConditions", typeof(AnswerCondition)),
.
.
.
};

foreach (KeyValuePair<string, Type> item in list)
 {
    string address = item.Key;
    Type t = item.Value;
    odataBuilder
     .EntitySet<t>(address)
     .EntityType
     .Select()
     .Expand()
     .OrderBy()
     .Filter()
     .Count();
 }

But it shows an error for t

't' is a variable but is used like a type

How can I store list of classes in a variable and used them later as generic type?

1 Answers

Using Reflection:

Type oDataType = odataBuilder.GetType();
MethodInfo genericMethod = oDataType.GetMethod("EntitySet", 1, new[] {typeof(string)});

foreach (KeyValuePair<string, Type> item in list)
 {
    string address = item.Key;
    Type t = item.Value;
    MethodInfo method = genericMethod.MakeGenericMethod(t);

    dynamic set = method.Invoke(odataBuilder, new object[]{address});
    set
     .EntityType
     .Select()
     .Expand()
     .OrderBy()
     .Filter()
     .Count();
 }
Related