2012-03-29 63 views
0

我使用EF按月,按天或按小时计算帖子。填充DateTime和Int间隙

我最终列出了DateTime/Int,其中有一些DateTime间隙。

的差距是年,年算起,在几个月,按月计算的时候,...

是否有写按年或月填补空白的日期时间延长的方式,...

甚至是另一个填补int空白的扩展?

谢谢你, 米格尔

回答

1

不看你的代码,你为什么不预填充你的表与所有的数,您所需要的时间(即无缺口)的0

Date  Count 
Jan2012 0 
Feb2012 0 
Mar2012 0 
... 
Dec2049 0 

这将保证你的名单永远不会有空白。您可以使用sql日期函数为这一代编写脚本,或使用Excel并导入到数据库中。

+0

这可能看起来很乱,但我会使用这个解决方案。简单。 – usr 2012-03-30 23:06:28

0

我在做什么基本上是这样的:

// Tupple to hold data 
IList<Tuple<DateTime, Int32>> data = new List<Tuple<DateTime, Int32>>(); 

// Get data from repository (Count by year) and add to Tupple 
_repository.Set<Post>() 
.Where(x => x.Created >= start && x.Created <= end) 
.GroupBy(x => new { Year = x.Created.Year }) 
.Select(x => new { Year = x.Key.Year, Count = x.Count() }) 
.ToList().ForEach(x => data.Add(new Tuple<DateTime, Int32>(new DateTime(x.Year, 1, 1), x.Count))); 

// Fill empty years with 0 as count 
for (Int32 i = 0; i <= (end - start).TotalYears; i++) 
    if (!data.Any(x => x.Item1 == start.AddYears(i))) 
    data.Add(new Tuple<DateTime, Int32>(start.AddYears(i), 0)); 

// Resort data 
data = data.OrderBy(x => x.Item1).ToList(); 

基本上,我一直在寻找一种方式,较少的步骤来做到这一点...

也许使用表联盟或加入...

我只是填补我使用的许多步骤...

谢谢你, 米格尔