Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting count in LINQ

Tags:

c#

.net

count

linq

I got a SQL Server table with columns ResolvedDate and ResolvedBy.

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.

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

How can I implement that?

like image 599
SeToY Avatar asked Apr 06 '12 18:04

SeToY


3 Answers

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()}
like image 126
Ralph Shillington Avatar answered Sep 19 '22 09:09

Ralph Shillington


If you're trying to count each item by date, you'd need to use 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() });
like image 42
Reed Copsey Avatar answered Sep 21 '22 09:09

Reed Copsey


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

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() }
like image 25
MarcinJuraszek Avatar answered Sep 19 '22 09:09

MarcinJuraszek