I have a complex object with a lot of Properties with string, decimal and ObservableColection, List...
I want to do this:
foreach (ITransactionItem transactionItem in Transaction.TransactionItemCollection.ToList())
{
transactionItem.PickUpQuantity = 0;
transactionItem.IsPickUp = false;
this.PickUpItemCollection.Add(transactionItem);
}
The problem is, when I change item in PickUpItemCollection, reference item in TransactionItemCollection is changed too and I don't want it.
I tried to use this ExtensionMethod to Copy object from object:
public static T CopyFrom<T>(this T toObject, object fromObject)
{
var fromObjectType = fromObject.GetType();
foreach (PropertyInfo toProperty in toObject.GetType().GetProperties())
{
PropertyInfo fromProperty = fromObjectType.GetProperty(toProperty.Name);
if (fromProperty != null) // match found
{
// check types
var fromType = Nullable.GetUnderlyingType(fromProperty.PropertyType) ?? fromProperty.PropertyType;
var toType = Nullable.GetUnderlyingType(toProperty.PropertyType) ?? toProperty.PropertyType;
if (toType.IsAssignableFrom(fromType)&& toProperty.CanWrite)
{
toProperty.SetValue(toObject, fromProperty.GetValue(fromObject, null), null);
}
}
}
return toObject;
}
and implement into this code block as:
foreach (ITransactionItem transactionItem in Transaction.TransactionItemCollection.AsEnumerable().ToList())
{
ITransactionItem transactionItemModel = new TransactionItemModel();
transactionItemModel.CopyFrom(transactionItem);
transactionItem.PickUpQuantity = 0;
transactionItem.IsPickUp = false;
this.PickUpItemCollection.Add(transactionItemModel);
}
But problem is still there, I know I can set property of transactionItemModel as property of transactionItem one by one but there are a lot of properties and it has a lot of List/ObservableCollection too. I think it would be have a better idea for this, right?
Please help me.
Thanks