Green 绿色
Green 绿色

Reputation: 2886

c#: Convert object to a generic list

I've got a data structure in which a variable is of type object. However, I know during runtime this object will be definitely a List<T>, where T should cover multiple cases (e.g., int, string, ...). In the following code, I'd like to use List<T>-specific functionality, such as Linq functions.

With the following check, I make sure, it's a list:

if (constantExpression.Value.GetType().GetGenericTypeDefinition() == typeof(List<>)) 
{
    // Want to use Linq here
}

Is this possible? Unfortunately, I've found nothing helpful on the Web.

Upvotes: 0

Views: 919

Answers (1)

Konamiman
Konamiman

Reputation: 50273

If it's ok for you to handle your list as a List<object>() you can do the following:

var listOfObjects = ((IEnumerable)constantExpression.Value).Cast<object>();

That's far from perfect but it's probably the best you can get if you don't want to resort to using reflection or using dynamic, as suggested in the comments.

Upvotes: 2

Related Questions