使用按日期查询的linq组填充数据表中缺少的日期

时间:2013-02-02 10:40:08

标签: c# asp.net

我正在尝试在数据表中填写缺少日期的报告。 例如:

数据表集合:

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() 
                   };

我该怎么做?

2 个答案:

答案 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);
}