1:建構實體,(注意:屬性數量一樣)
public class C1
{
public string age { get; set; }
public string name { get; set; }
}
public class C2
{
public string 年齡 { get; set; }
public string 姓名 { get; set; }
}
2:填充資料:
var list = new List<C1>();
list.Add(new C1
{
age = "11",
name = "admin"
});
list.Add(new C1
{
age = "22",
name = "張三"
});
3:方法調用: var newlist = ConvertToNewModel<C1, C2>(list);
4:方法:
public static List<T2> ConvertToNewModel<T1, T2>(List<T1> list)
{
var t2 = new List<T2>();
foreach (var item in list)
{
T2 model = default(T2);
model = Activator.CreateInstance<T2>();
PropertyInfo[] pi1 = typeof(T1).GetProperties();
PropertyInfo[] propertys = model.GetType().GetProperties();
for (int i = 0; i < propertys.Count(); i++)
{
propertys[i].SetValue(model, pi1[i].GetValue(item, null), null);
}
t2.Add(model);
}
return t2;
}