Toto
Toto

Reputation: 7719

List of object to List of predetermined type

How to convert an original list to an other one in the more generic way. The destination type is only known at runtime.

I tried the following, but I got a List<object> filled with element of DestinationType type.

    public static object ToList(List<object> original,Type destinationType)
    {
        return
            original
                .Select(v => Convert.ChangeType(v, destinationType, CultureInfo.InvariantCulture))
                .ToList();//List<object> is returned, I want a List<destinationType>
    }

Upvotes: 1

Views: 77

Answers (2)

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73502

If you can make the method generic this is the best solution.

    public static object ToList<T>(List<object> original)
    {
        var type = typeof(T);
        return original
                     .Select(v => (T)Convert.ChangeType(v, type, CultureInfo.InvariantCulture))
                     .ToList();
    }

Else, Go with @Rafal's solution..

Upvotes: 2

Rafal
Rafal

Reputation: 12639

Try this:

var list = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(destinationType));

foreach (var element in original)
{
    var converted = Convert.ChangeType(element, destinationType, CultureInfo.InvariantCulture);
    list.Add(converted);
}

return list;

Code creates instance of List<destinationType> in runtime then adds all converted elements to it and returns it.

Upvotes: 2

Related Questions