网上找了好多资料关于操作DataTable示例,但都不能对其进行top的方法,下面有一个比较好的方法: /// Gets the latest comments. /// /// The comments. /// The num comments. /// The sort id. /// public DataView GetTopComments(DataView Comments, int numComments, string sortId) { string filter = string.Empty; string delimiter = string.Empty; numComments = Math.Min(numComments, Comments.Count); for (int i = 0; i < numComments; i++) { filter += delimiter + Comments[i][sortId].ToString(); delimiter = ","; } if (filter.Length > 0) { Comments.RowFilter = sortId + " in (" + filter + ")"; } return Comments; }
操作示例: DataTable dt = GetTable(); DataView dv = dt.DefaultView; DataTable newDt = GetTopComments(dv, 18).Table;
根据对其研究后,自己总结了一个下面的方法:如下
个人项目示例精典的top 1方法: ////// 操作dt /// /// 表名 /// 条件字符串 /// 所需值字段 /// 排序的列的位置 /// 是否为降序 private void SetDTValue(DataTable dt, string valueName, DateTime time_st, int rownum, int OrderColumnIndex, bool IsDesc) { //dt = DataAccess.OrderDataTable(dt, 0, false); if (dt.Rows.Count > 0) { if (dt.Columns.Contains("time_stamp")) { //递归方法进行查找 for (int i = 2; i < 14; i++) { DataRow[] rows = dt.Select(" time_stamp >= '" + time_st.AddMinutes((i - 2) * 5) + "' and time_stamp < '" + time_st.AddMinutes((i - 1) * 5) + "'"); DataTable ndt = dt.Clone(); for (int j = 0; j < rows.Length; j++) { ndt.ImportRow(rows[j]); } if (ndt.Rows.Count > 0) { DataView dv = ndt.DefaultView; string OrderCondition = ndt.Columns[OrderColumnIndex].ToString(); //编辑排序的条件 if (IsDesc) OrderCondition += " desc"; dv.Sort = OrderCondition; //对DataView 进行排序 DataTable NewDataTable = ndt.Clone(); //建立返回的datatable for (int index = 0; index < dv.Count; index++) { DataRow Dr = NewDataTable.NewRow(); for (int pin = 0; pin < NewDataTable.Columns.Count; pin++) { Dr[pin] = dv[index][pin]; } NewDataTable.Rows.Add(Dr); } data[rownum, i] = NewDataTable.Rows[0][1].ToString();//取其第一个! ndt.Clear(); NewDataTable.Clear(); } } } } dt.Clear(); }
//以上的个人示例可以做成一个类,这里就不必多说了!