鑑於以下數據:
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));
的obvoius 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
部分時間,並使用DataView
來做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
,你可以先複製它。
爲什麼不使用LINQ? – 2012-08-16 12:41:00