c# - Generic Collection copying method -


i've got useful little method uses reflection copy single class instance. has advantage of letting copy between classes not same, copying matching properties. use lot.

public static void objectcopy(object source, object target) {     if (source != null && target != null)     {         foreach (var prop in target.gettype().getproperties())         {             var fromprop = source.gettype().getproperty(prop.name);             if (fromprop != null)             {                 prop.setvalue(target, fromprop.getvalue(source));             }         }     } } 

i've got requirement similar thing, collection, ie observablecollection or list. i'm struggling figure out how in generic routine. can call old routine within new 1 collection item copying handling collection i'm struggling with.

any ideas?


i need able copy collection of different (but similar) classes. example being observablecollection observablecollection. have common properties differences.

sorry not being more specific.

this might it. works on collections.

public static void objectcollection<tc, tk>(icollection source, tc target)     tc : class, icollection<tk>, new()     tk : class, new() {     foreach (var item in source)     {         var copieditem = new tk();         objectcopy(item, copieditem);         target.add(copieditem);     } } 

example usage:

public class data { public string test { get; set; } } public class data2 { public string test { get; set; } }  var source = new data[3] {     new data { test = "1" },     new data { test = "2" },     new data { test = "3" } }; var target = new list<data2>(); objectcollection<list<data2>, data2>(source, target); 

Comments