Search code examples
c#linqt-sqllinq-to-entitiescomparable

Write a comparable LINQ query for aggregate distinct count in sql?


I want to get a count for each month but count should be only at most one per day even if there are multiple occurences . I have the SQL query which works right but having trouble to convert it into LINQ -

select 
    count(DISTINCT DAY(date)) as Monthly_Count,
    MONTH(date) as Month,
    YEAR(date)
from 
    activity
where 
    id=@id
group by
    YEAR(date),
    MONTH(date) 

Could anyone help me translating the above query to LINQ. Thanks!


Solution

  • Per LINQ to SQL using GROUP BY and COUNT(DISTINCT) given by @Rick, this should work:

    var query = from act in db.Activity
                where act.Id == id
                group act by new { act.Date.Year, act.Date.Month } into g
                select new
                {
                    MonthlyCount = g.Select(act => act.Date.Day).Distinct().Count(),
                    Month = g.Key.Month,
                    Year = g.Key.Year
                };
    

    I don't know if L2S can convert the inner g.Select(act => act.Date.Day).Distinct.Count() properly.