2013-02-02 37 views
0

我试图在数据表中填写报告缺失的日期。 例如:用日期查询填写数据表中缺少日期使用linq组按日期查询

数据表收集:

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

只是使用循环迭代数据表并插入缺失的日期。 – TechDo

+0

code please ..... – daryal

+0

var total = from dt2.AsEnumerable() where row.Field (“Super Category”)== j group by row.Field (“Activation Date”)into销售 的OrderBy sales.Key 选择新 { 名称= sales.Key, CountOfClients = sales.Count() }; –

回答

0

尝试类似这样的事情。

DateTime startDate = collection.first().date; 
DateTime endDate = collection.last().date; 

While(startDate < endDate) 
{ 
    // compare if collection date is valid 
    startDate.AddDays(1); 
} 
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差距。