Huzefa
Huzefa

Reputation:

Convert Object type to List<T>

I have an object which can be of any collection type like IEnumerable or IQueryable or List.
Now i want this object to be converted into type List.
Can anyone tell me how can i achieve this??

Thanks

Upvotes: 0

Views: 1989

Answers (2)

Meta-Knight
Meta-Knight

Reputation: 17845

You could cast your object to IEnumerable(T), then call ToList on it (.NET 3.5 required).

Upvotes: 1

Keith
Keith

Reputation: 155602

If you have .net 3.5 and System.Linq:

List<NewType> converted =
    myUnknownEnumeration.OfType<NewType>().ToList();

You need OfType to do the conversion (you can use Cast<>() instead if you want to throw an exception for any of the the wrong type) and ToList converts anything enumerable into a list.

Upvotes: 5

Related Questions