使用 LINQ 获取 2 个日期之间的日期发生次数

Get count of date occurrence between 2 dates using LINQ

我有一个 table 消息。我有一个消息日期字段。我想计算 messagedate 在 2 个日期之间出现了多少次。

我在 linq 中制定查询时遇到问题。

string currYear = DateTime.Now.Year.ToString();
var TotalSmsJan = (from x in db.Messages
                                     where (x.MessageDate  >= '1/1/@currYear') && (x.MessageDate >= '1 /31/@currYear')   
                                     select x).Count();

理想情况下,我希望每个月都有消息计数,但很乐意像上面的代码那样一次获取一条消息。

像在您的代码中那样将字符串视为日期并不是最佳选择。

以下代码使用日期而不是字符串,并使用与您当前代码相同的基本结构。它需要 12 个查询(每个月一个)。

var currYear = DateTime.Now.Year;

for (int month = 1; month <= 12; month++)
{
    var firstOfThisMonth = new DateTime(currYear, month, 1);
    var firstOfNextMonth = firstOfThisMonth.AddMonths(1);

    var totalSMS = (from x in db.Messages
                    where x.MessageDate >= firstOfThisMonth && x.MessageDate < firstOfNextMonth
                    select x).Count();
}

这是您的原始 Linq 语句:

string currYear = DateTime.Now.Year.ToString();
var TotalSmsJan = (from x in db.Messages
                                     where (x.MessageDate  >= '1/1/@currYear') && (x.MessageDate >= '1 /31/@currYear')   
                                     select x).Count();

你在问:

Ideally I would like the message count for each month, but would be happy to get them one at a time as in code above.

您可以将其更改为:

string currYear = DateTime.Now.Year.ToString();
var TotalSmsJan = (from x in db.Messages
                                     where (x.MessageDate  >= '1/1/@currYear') && (x.MessageDate >= '1 /31/@currYear')   
                                     select x);
var totalCount = TotalSmsJan.Count();
var totalForPeriod = TotalSmsJan.Where(s => s.MessageDate >= 'your lower date' && s.MessageDate <= 'your upper date').Count();