C# 在 LINQ 中选择计数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10047942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 12:15:17  来源:igfitidea点击:

Selecting count in LINQ

c#.netlinqcount

提问by SeToY

I got a SQL Server table with columns ResolvedDateand ResolvedBy.

我得到了一个包含列ResolvedDateResolvedBy.

Now I want to select those two columns and count their results, which I thought I'd implement like that:

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

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

As you can see, the Count-Part is missing.

如您所见,缺少 Count-Part。

I want to get every activity, that has been done in this ResolvedDate and count it.

我想获取在此 ResolvedDate 中完成的所有活动并对其进行计数。

How can I implement that?

我该如何实施?

采纳答案by Ralph Shillington

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

回答by SLaks

var dates = dataContext.Activities
    .Where(a => a.IsResolved && a.ResolvedBy == userId)
    .Select(a => a.ResolvedDate)
    .ToList();

var count = dates.Count;

If you only want to get the count, you can make it much faster by selecting the count alone:

如果你只想得到计数,你可以通过单独选择计数来使它更快:

var count = dataContext.Activities
    .Count(a => a.IsResolved && a.ResolvedBy == userId);

回答by Reed Copsey

If you're trying to count each item by date, you'd need to use GroupBy:

如果您尝试按日期计算每个项目,则需要使用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() });

回答by MarcinJuraszek

You have to group your data by ResolvedDate to get number of activities resolved every day.

您必须按 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() }

To group just by day (without hour, minutes, etc.) you can change the group statement:

要按天分组(没有小时、分钟等),您可以更改组语句:

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