c# - List of object to List of predetermined type -


how convert original list other 1 in more generic way. destination type known @ runtime.

i tried following, got list<object> filled 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> returned, want list<destinationtype>     } 

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 adds converted elements , returns it.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -