linq groupby question
I have a table that has several columns: HarvestID, HarvestDate, UserID to mention the main ones. For each date, there are going to be several HarvestID per day.
So far, I have the following linq query:
TheUserID and TheMonth are passed in as an int and a DateTime
var MyQuery = from h in MyDC.HarvestTable
where h.UserID == TheUserID
where h.HarvestDate.Month == TheMonth.Month
where h.HarvestDate.Year == TheMonth.Year
group h by h.HarvestDate.Day into TheDays
from d in TheDays
select new
{
TheDay = d.HarvestDate.Date,
TheDayCount = (from c in TheDay
select c.HarvestID).Count()
};
I'm looking to have the output be a list of counts per day. The query doesn't bug but the problem is that at the moment the query is not returning a unique row for each day. The grouping doesn't work and I'm not finding out why. What's wrong with this code?
Thanks.
It think your query should be
var MyQuery = from h in MyDC.HarvestTable
where h.UserID == TheUserID
where h.HarvestDate.Month == TheMonth.Month
where h.HarvestDate.Year == TheMonth.Year
group h by h.HarvestDate.Day into TheDays
select new
{
TheDay = TheDays.Key,
TheDayCount = TheDays.Count()
};
Here is a vry good refrence to above group by statement http://msdn.microsoft.com/en-us/vcsharp/aa336754.aspx#simple1
var MyQuery = from h in MyDC.HarvestTable
where h.UserID == TheUserID
&& h.HarvestDate.Month == TheMonth.Month
&& h.HarvestDate.Year == TheMonth.Year
group h by h.HarvestDate.Day into g
select new
{
TheDay = g.Key,
TheDayCount = g.Count()
};
This will not give you zeroes on the days where there is no data - but should give you a count where there is.
http://msdn.microsoft.com/en-us/vcsharp/aa336746 is my go-to page for LINQ examples.
链接地址: http://www.djcxy.com/p/31906.html上一篇: linq where语句与OR
下一篇: linq groupby问题