DataTable物件系列化後可以用Linq獲取值方法
阿新 • • 發佈:2019-02-06
系統化後可以用linq,不用迴圈語句,要方便很多,獲取值方法:
//類 public class User { public int ID { get; set; } public string Name { get; set; } } //物件轉換 private static List<T> TableToEntity<T>(DataTable dt) where T : class,new() { Type type = typeof(T); List<T> list = new List<T>(); foreach (DataRow row in dt.Rows) { PropertyInfo[] pArray = type.GetProperties(); T entity = new T(); foreach (PropertyInfo p in pArray) { if (row[p.Name] is Int64) { p.SetValue(entity, Convert.ToInt32(row[p.Name]), null); continue; } p.SetValue(entity, row[p.Name], null); } list.Add(entity); } return list; } // 呼叫: List<User> userList = TableToEntity<User>(YourDataTable); --獲取table內的一欄位值 int count1=dtOrderDetails.AsEnumerable().Where(t => t.Field<string>("SKU").Substring(0, 2) == "MH" || t.Field<string>("SKU").Substring(0, 2) == "MK").Count() int count2=dtOrderDetails.AsEnumerable().Where(e => e.Field<decimal>("UnitPrice") == 0 || e.Field<decimal>("SalesPrice") == 0).Count() int count3=dtOrderDetails.AsEnumerable().Where(e => e.Field<int>("BType") == 1 && e.Field<string>("BValue") == MemberID.ToString()).Count()