My code works fine and I am just wondering is there a more efficient way to copy a similar list to another and ignore the properties which are not present.
private const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.SetProperty;
public static List<T> MergeListData<T>(List<object> collection)
{
if (collection == null)
throw new ArgumentNullException("Collection", "The Collection that you are copying to cannot be null");
List<T> result = new List<T>();
for (int x = 0; x < collection.Count; x++)
{
var target = (T)Activator.CreateInstance(typeof(T));
var propInfos = collection[x].GetType().GetProperties(flags);
for (int i = 0; i < propInfos.Length; i++)
{
try
{
PropertyInfo _propinfo = target.GetType().GetProperty(propInfos[i].Name, flags);
if (_propinfo != null)
_propinfo.SetValue(target, Nullable.GetUnderlyingType(propInfos[i].PropertyType) ?? propInfos[i].GetValue(collection[x]));
}
catch (ArgumentException aex) { if (!string.IsNullOrEmpty(aex.Message)) continue; }
catch (Exception ex) { if (!string.IsNullOrEmpty(ex.Message)) return default(List<T>); }
}
result.Add(target);
}
return result;
}
And the usage is:
public class Name1
{
public int Number { get; set; }
public string First { get; set; }
public string Last { get; set; }
}
public class Name2
{
public string First { get; set; }
public string Last { get; set; }
public decimal Wages { get; set; }
public bool Active { get; set; }
}
var List1 = new List<Name1> { new Name1{ First = "Billy", Number = 1, Last = "Harte"}, new Name1 { First = "Jimmy", Number = 1, Last = "Dunne" } };
List<Name2> bs = MergeListData<Name2>(List1.Select(x => x as object).ToList());