using System; using System.Collections.Generic; using System.Data; using System.Reflection; namespace EC.Utils { /// /// ExtTable /// 版 本:V3.0.0 /// 版 权:EasyCode /// 作 者:LXC /// public static class ExtTable { /// /// 获取表里某页的数据 /// /// 表数据 /// 当前页 /// 分页大小 /// 返回总页数 /// 返回当页表数据 public static DataTable GetPage(this DataTable data, int pageIndex, int pageSize, out int allPage) { allPage = data.Rows.Count / pageSize; allPage += data.Rows.Count % pageSize == 0 ? 0 : 1; DataTable Ntable = data.Clone(); int startIndex = pageIndex * pageSize; int endIndex = startIndex + pageSize > data.Rows.Count ? data.Rows.Count : startIndex + pageSize; if (startIndex < endIndex) for (int i = startIndex; i < endIndex; i++) { Ntable.ImportRow(data.Rows[i]); } return Ntable; } /// /// 根据字段过滤表的内容 /// /// 表数据 /// 条件 /// /// public static DataTable GetDataFilter(DataTable data, string condition) { if (data != null && data.Rows.Count > 0) { if (condition.Trim() == "") { return data; } else { DataTable newdt = new DataTable(); newdt = data.Clone(); DataRow[] dr = data.Select(condition); for (int i = 0; i < dr.Length; i++) { newdt.ImportRow((DataRow)dr[i]); } return newdt; } } else { return null; } } /// /// 获取表里前几条数据 /// /// 表数据 /// /// public static DataTable GetSelectTop(DataTable data, int top) { if (data.Rows.Count < top) return data; DataTable NewTable = data.Clone(); DataRow[] rows = data.Select("1=1"); for (int i = 0; i < top; i++) { NewTable.ImportRow((DataRow)rows[i]); } return NewTable; } /// /// List转化一个DataTable /// /// /// /// public static DataTable ToDataTable(this IEnumerable list) { List pList = new List(); Type type = typeof(T); DataTable dt = new DataTable(); Array.ForEach(type.GetProperties(), p => { pList.Add(p); dt.Columns.Add(p.Name); }); foreach (var item in list) { DataRow row = dt.NewRow(); pList.ForEach(p => row[p.Name] = p.GetValue(item, null)); dt.Rows.Add(row); } return dt; } } }