给定以下数据:
var dt = new DataTable();
dt.Columns.Add(new DataColumn("Time", typeof(DateTime)));
dt.Rows.Add(new DateTime(2000, 12, 31, 12, 0, 0));
dt.Rows.Add(new DateTime(2000, 12, 31, 12, 0, 0));
dt.Rows.Add(new DateTime(2000, 12, 31, 12, 0, 1));
dt.Rows.Add(new DateTime(2000, 12, 31, 12, 0, 2));
dt.Rows.Add(new DateTime(2000, 12, 31, 12, 4, 2));
dt.Rows.Add(new DateTime(2000, 12, 31, 12, 5, 5));
dt.Rows.Add(new DateTime(2000, 12, 31, 12, 5, 2));
显而易见的 Linq 方法是
var result = from row in dt.AsEnumerable()
let d = row.Field<DateTime>("Time")
group row by new DateTime(d.Year, d.Month, d.Day, d.Hour, d.Minute, 0) into g
select g.First();
foreach (DataRow row in result)
Console.WriteLine(row["Time"]);
但是既然您要求使用非 linq 解决方案,为什么不只遍历每一行,摆脱seconds
部分时间,并使用 aDataView
来完成该Distinct
部分:
foreach (DataRow row in dt.Rows)
{
DateTime d = row.Field<DateTime>("Time");
row["Time"] = new DateTime(d.Year, d.Month, d.Day, d.Hour, d.Minute, 0);
// or use "tricks" like this
// row["Time"] = d.AddTicks(-(d.Ticks % TimeSpan.TicksPerMinute));
}
foreach(DataRow r in new DataView(dt).ToTable(true).Rows)
Console.WriteLine(r["Time"]);
如果你不想改变你的DataTable
,你可以先复制它。