C#功能块代码
//dtPerson 为表,FName为表里面的字段 string[] personArry = dtPerson.AsEnumerable().Select(d => d.Field<string>("FName")).ToArray();
public static D Mapper<D, S>(S s) { D d = Activator.CreateInstance<D>(); //构造新实例 try { var Types = s.GetType();//获得类型 var Typed = typeof(D); foreach (PropertyInfo sp in Types.GetProperties())//获得类型的属性字段 { foreach (PropertyInfo dp in Typed.GetProperties()) { if (dp.Name == sp.Name && dp.PropertyType == sp.PropertyType && dp.Name != "Error" && dp.Name != "Item")//判断属性名是否相同 { dp.SetValue(d, sp.GetValue(s, null), null);//获得s对象属性的值复制给d对象的属性 } } } } catch (Exception ex) { throw ex; } return d; } //使用示例 PTLLocalDB.T_SAP_PurchaseHeaderInfo PTLHeader = new PTLLocalDB.T_SAP_PurchaseHeaderInfo(); PTLHeader = PTLStartSAPFlow.Mapper<PTLLocalDB.T_SAP_PurchaseHeaderInfo, LocalDB.T_SAP_PurchaseHeaderInfo>(header);
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace AirTicketWinform { public class ModelConvertHelper<T> where T : new() { public static List<T> ConvertToModel(DataTable dt) { // 定义集合 List<T> ts = new List<T>(); // 获得此模型的类型 Type type = typeof(T); string tempName = ""; foreach (DataRow dr in dt.Rows) { T t = new T(); // 获得此模型的公共属性 PropertyInfo[] propertys = t.GetType().GetProperties(); foreach (PropertyInfo pi in propertys) { tempName = pi.Name; // 检查DataTable是否包含此列 if (dt.Columns.Contains(tempName)) { // 判断此属性是否有Setter if (!pi.CanWrite) continue; object value = dr[tempName]; if (value != DBNull.Value) pi.SetValue(t, value, null); } } ts.Add(t); } return ts; } } } 调用方式 MFG_DAILY_MANPOWER 为model 类名 DataTable showTable = new DataTable(); showTable.Columns.Add("divsion",typeof(string)); showTable.Columns.Add("DepartCode", typeof(string)); DataRow dr = showTable.NewRow(); dr["divsion"] = "A"; dr["DepartCode"] = "DA1"; showTable.Rows.InsertAt(dr,0); //string result = mfgBLL.DataTableToJson(showTable); //string[] arr = showTable.AsEnumerable().Select(d=>d.).ToArray(); List<MFG_DAILY_MANPOWER> ls = ModelConvertHelper<MFG_DAILY_MANPOWER>.ConvertToModel(showTable); return Json(new { data = ls, msg = "上次成功" }, JsonRequestBehavior.AllowGet);