简体   繁体   中英

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 (eg, 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM