5

我有一个带有列的 SQL Server 表ResolvedDateResolvedBy.

现在我想选择这两列并计算它们的结果,我想我会这样实现:

_dataContext.Activities
    .Where(a => a.IsResolved && a.ResolvedBy == userId)
    .Select(a => new { a.ResolvedDate, ***COUNT*** });

如您所见,缺少 Count-Part。

我想得到在这个 ResolvedDate 中完成的每一个活动并计算它。

我该如何实施?

4

4 回答 4

18
from a in dataContext.Activities
where a.IsResolved && a.ResolvedBy == userId
group a by a.ResolvedDate into g
select new {ResolvedOn=g.Key, NumberResolved= g.Count()}
于 2012-04-06T18:58:29.257 回答
10

如果您尝试按日期计算每个项目,则需要使用GroupBy

var countsByDate = _dateContext.Activities
                           .Where(a => a.IsResolved && a.ResolvedBy == userId)
                           .GroupBy(a => a.ResolvedDate)
                           .Select(g => new {ResolvedDate = g.Key, Count = g.Count() });
于 2012-04-06T18:58:41.497 回答
6

您必须按 ResolvedDate 对数据进行分组,以获取每天解决的活动数量。

var dates = from a in dataContext.Activities
            where a.IsResolved && a.ResolvedBy == userId
            group a by a.ResolvedDate into g
            select new { Date = g.Key, Count = g.Count() }

要按天分组(不包括小时、分钟等),您可以更改 group 语句:

var dates = from a in dataContext.Activities
            where a.IsResolved && a.ResolvedBy == userId
            group a by a.ResolvedDate.Date into g
            select new { Date = g.Key, Count = g.Count() }
于 2012-04-06T18:59:57.060 回答
3
var dates = dataContext.Activities
    .Where(a => a.IsResolved && a.ResolvedBy == userId)
    .Select(a => a.ResolvedDate)
    .ToList();

var count = dates.Count;

如果您只想获取计数,则可以通过单独选择计数来使其更快:

var count = dataContext.Activities
    .Count(a => a.IsResolved && a.ResolvedBy == userId);
于 2012-04-06T18:57:16.717 回答