用Linq 先根据查询结果用时间排序,再用Linq的Distinct()方法对action重复值做过滤。给你个例子
DataTable dt=new DataTable(); dt.Columns.Add("action"); dt.Columns.Add("date"); dt.Columns["date"].DataType = typeof (DateTime); DataRow dr = dt.NewRow(); dr["action"] = "aaaa"; dr["date"] =Convert.ToDateTime("2012-2-3 12:11:22"); dt.Rows.Add(dr); dr = dt.NewRow(); dr["action"] = "bbbb"; dr["date"] = Convert.ToDateTime("2012-2-3 12:25:22"); dt.Rows.Add(dr); dr = dt.NewRow(); dr["action"] = "aaaa"; dr["date"] = Convert.ToDateTime("2012-2-3 12:22:22"); dt.Rows.Add(dr); var drs = (from data in dt.AsEnumerable() orderby data["date"] descending select data).Distinct(new DataRowCompare());//根据时间反序排序获取结果 foreach (DataRow dataRow in drs) { Console.WriteLine("{0}-{1}",dataRow["date"],dataRow["action"]); } Console.ReadLine(); } //过滤条件,根据action过滤 public class DataRowCompare : IEqualityComparer<DataRow> { public bool Equals(DataRow x, DataRow y) { return x["action"] == y["action"]; } public int GetHashCode(DataRow obj) { return obj["action"].ToString().GetHashCode(); } }
select action,max(date) date from table group by action order by date desc
datatable 可以这样查询吗?
呵呵。。。
datatable没办法满足你的要求,你可以先转换成List,再用list来查,再转换回datatable
能不能给演示一下啊?呵呵
排序:
DataView dv = new DataView(); dv = dt.DefaultView; dv.Sort = "date"; //排序 dt = dv.ToTable();
action的唯一性:
list<string> sameList=new list<string>(); for(int i=dt.Rows.count-1;i>=0;i--) { DataRow row =dt.Rows[i]; string action=row["action"].tostring(); if(sameList.Contains(action)) row.delete(); else sameList.Add(action); } dt.AcceptChanges();