2013-09-30 87 views
1

我有以下代码,其中列出了顶部3'名称'按降序排列,并记录了'name'在表格中出现的次数。这工作正常。使用Linq获取当前月份的数据 - VB

Dim top3 = From s In dc.Suggestions 
       Group By Name = s.name 
       Into t3 = Group, Count() 
       Order By Count Descending 
       Take 3 

我想修改这个,以便它只会得到每个'name'出现在当前月份的记录数。我可以使用s.dateRaised来获取记录的日期,但我不完全确定如何编写代码以获取当前月份的记录?

+0

'where Month(s.dateRaised)= Month(DateTime.Now)'? –

回答

2

这是对卡尔答案的微小修改。我喜欢这个更好一点,因为他的回答在本月的最后一天的最后一分钟不会包含任何具有dateRaised价值的东西。

Dim CurrentYear As Integer = DateTime.Today.Year 
Dim CurrentMonth As Integer = DateTime.Today.Month 

Dim startOfCurrentMonthDate As New DateTime(CurrentYear, CurrentMonth, 1) 
Dim startOfNextMonthDate As DateTime = startOfCurrentMonthDate.AddMonths(1) 

Dim top3 = From s In dc.Suggestions 
      Where s.dateRaised >= startOfCurrentMonthDate AndAlso 
       s.dateRaised < startOfNextMonthDate 
      Group By Name = s.name 
      Into t3 = Group, Count() 
      Order By Count Descending 
      Take 3 
+0

谢谢道格拉斯,一个小问题。 dateRaised是数据类型nvarchar,所以我得到错误'nvarchar数据类型转换为日期时间数据类型导致超出范围值' – Jimsan

+0

在这种情况下,请使用'CDate','DateTime。解析“或”Convert.ToDateTime“将其更改为日期时间。 –

1

首先你得开始和当前月底,像这样:

Dim CurrentYear As Integer = DateTime.Today.Year 
Dim CurrentMonth As Integer = DateTime.Today.Month 

Dim startOfCurrentMonthDate As New DateTime(CurrentYear, CurrentMonth, 1) 
Dim endOfCurrentMonthDate As DateTime = startDate.AddMonths(1).AddMinutes(-1) 

现在,你需要使用的开始和结束日期在Where,像这样:

Dim top3 = From s In dc.Suggestions 
      Where s.dateRaised >= startOfCurrentMonthDate And 
       s.dateRaised <= endOfCurrentMonthDate 
      Group By Name = s.name 
      Into t3 = Group, Count() 
      Order By Count Descending 
      Take 3 
+0

是不是有没有使用'startDate.AddMonths(1).AddTicks(-1)'或者简单的'startDate.AddMonths(1)'和一个小于检查的原因? –

相关问题