I've got this useful little method that uses reflection to copy a single class instance. It has the advantage of letting you copy between classes that are not exactly the same, just copying the matching properties. I use it a 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 now got a requirement to do a similar thing, but with a collection, ie an ObservableCollection or List. I'm struggling to figure out how to do this in a generic routine. I can call the old routine from within the new one to do the collection item copying but handling the collection itself is what I'm struggling with.
Any ideas?
I need to be able to copy collection of different (but similar) classes. My example being an ObservableCollection into an ObservableCollection. They have common properties but also some differences.
Sorry for not being more specific.
This might do it. Only works on collections.
public static void ObjectCollection<TC, TK>(ICollection source, TC target)
where TC : class, ICollection<TK>, new()
where 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);
You could try something like the following to join together two existing collections of different type:
public static void MapCollections<T1, T2, TKey>(IEnumerable<T1> target, IEnumerable<T2> values,
Func<T1, TKey> targetKeySelector, Func<T2, TKey> valueKeySelector)
{
foreach (var pair in target.Join(values, targetKeySelector, valueKeySelector, (t, v) => new { target = t, value = v}))
{
ObjectCopy(pair.value, pair.target);
}
}
You might need to work in some additional constraints to manage duplicate keys etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With