Selecting count in LINQ

后端 未结 4 981
忘掉有多难
忘掉有多难 2021-01-14 00:50

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

相关标签:
4条回答
  • 2021-01-14 00:57

    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() });
    
    0 讨论(0)
  • 2021-01-14 01:02
    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);
    
    0 讨论(0)
  • 2021-01-14 01:06

    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() }
    
    0 讨论(0)
  • 2021-01-14 01:23
    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()}
    
    0 讨论(0)
提交回复
热议问题