我正在尝试在数据表中填写缺少日期的报告。 例如:
数据表集合:
2010-01-01 : 5
2010-01-02 : 4
2010-01-03 : 2
2010-01-05 : 6
但我想要这样的结果:
2010-01-01 : 5
2010-01-02 : 4
2010-01-03 : 2
2010-01-04 : 0
2010-01-05 : 6
var total = from row in dt2.AsEnumerable()
where row.Field<UInt32>("Super Category") == j
group row by row.Field<string>("Activation Date") into sales
orderby sales.Key
select new
{
Name = sales.Key,
CountOfClients = sales.Count()
};
我该怎么做?
答案 0 :(得分:1)
这有效:
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("dt", typeof(DateTime)));
dt.Columns.Add(new DataColumn("num", typeof(int)));
dt.Rows.Add(new DateTime(2010, 1, 1), 5);
dt.Rows.Add(new DateTime(2010, 1, 2), 4);
dt.Rows.Add(new DateTime(2010, 1, 3), 2);
dt.Rows.Add(new DateTime(2010, 1, 5), 6);
dt.Rows.Add(new DateTime(2010, 1, 8), 6);
dt.Rows.Add(new DateTime(2010, 1, 9), 6);
dt.Rows.Add(new DateTime(2010, 1, 12), 6);
DateTime minDT = dt.Rows.Cast<DataRow>().Min(row => (DateTime)row["dt"]);
DateTime maxDT = dt.Rows.Cast<DataRow>().Max(row => (DateTime)row["dt"]);
// Create all the dates that should be in table
List<DateTime> dts = new List<DateTime>();
DateTime DT = minDT;
while (DT <= maxDT)
{
dts.Add(DT);
DT = DT.AddDays(1);
}
// Find the dates that should be in table but aren't
var DTsNotInTable = dts.Except(dt.Rows.Cast<DataRow>().Select(row => (DateTime)row["dt"]));
foreach (DateTime dateTime in DTsNotInTable)
dt.Rows.Add(dateTime, 0);
// Order the results collection
var ordered = dt.Rows.Cast<DataRow>().OrderBy(row => (DateTime)row["dt"]);
// Create a DataTable object
DataTable dt2 = ordered.CopyToDataTable();
dt2
表格将包含DateTime
列未排列DateTime
个缺口的结果。
答案 1 :(得分:0)
尝试这样的事情。
DateTime startDate = collection.first().date;
DateTime endDate = collection.last().date;
While(startDate < endDate)
{
// compare if collection date is valid
startDate.AddDays(1);
}