我有以下代码,它按降序列出前3个'名称',并计算表中出现“名称”的记录数。这工作正常。
Dim top3 = From s In dc.Suggestions
Group By Name = s.name
Into t3 = Group, Count()
Order By Count Descending
Take 3
我想对此进行修改,以便只计算当前月份中每个“名称”出现的记录数。我可以使用s.dateRaised来获取记录的日期,但我不完全确定如何编写代码以仅获取当前月份的记录?
答案 0 :(得分: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
答案 1 :(得分: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