mercredi 17 juin 2020

Retrieving a collection from a generic method with a run time generic type

I have a generic method

var propertyResolverMethod = _propertyResolver
    .GetType()
    .GetMethod(
        nameof(_propertyResolver.GetEntities),
        new[] { typeof(string), typeof(string) })
    ?.MakeGenericMethod(_itemType);

and the invocation

var recommendedItems = propertyResolverMethod
    ?.Invoke(
        _propertyResolver,
        new object[] { itemId, ResolvedCollectionId });

It on the compile-time it returns an object, but on runtime, it returns IQueryable<Item> this item is the item from _itemType and we find out its type only on runtime, but I know that it has a collection inside Item.RelatedItems that I need to get. Tried already casting to dynamic, but does not work for my case, I know that's somehow solvable via Expressions.

Should be iteratable like this

var itemIds = recommendedItems?.Select(i => i.RelatedItems.Select(s => s.ItemID));

But it's not possible without a proper cast





Aucun commentaire:

Enregistrer un commentaire