在LINQ中选择计数

时间:2012-04-06 18:55:45

标签: c# .net linq count

我有一个包含ResolvedDateResolvedBy列的SQL Server表。

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

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

如您所见,Count-Part缺失。

我希望获得已在此ResolvedDate中完成的所有活动并计算它。

我该如何实现?

4 个答案:

答案 0 :(得分: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()}

答案 1 :(得分:9)

如果您要按日期计算每件商品,则需要使用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() });

答案 2 :(得分: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() }

要按天分组(不分小时,分钟等),您可以更改群组声明:

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() }

答案 3 :(得分:4)

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);