I have this code which I'm trying to use in retrieving the fish pond with the highest use of feed in a month, so I need to group by Pool_Name
, sum
feed usage and then select
the highest record after sorting.
Here's an example code:
var hfeed = db.feed_fish
.Where(x => (DbFunctions.TruncateTime(x.Feed_Time) >= frm
&& DbFunctions.TruncateTime(x.Feed_Time) <= todat))
.GroupBy(x => x.Pond_Name)
.Select(y => new feed_fish
{
Pond_Name = y.Key,
Total_feed_weight = y.Sum(d => d.Total_feed_weight)
})
.OrderByDescending(y=>y.Total_feed_weight).First();
A sample of the data...
Pond_Name Total_Feed_Weight
Pond 1 56
Pond 2 33
Pond 1 45
Pond 2 54
What I need to return is a list or iQueryable that totals the Total_feed_weight and returns the highest so...
Pond 1 101
Pond 2 87
I should be also able to access first so I get the highest consuming pond.
Updated
List<feed_fish> hfeed = db.feed_fish.Where(x => (DbFunctions.TruncateTime(x.Feed_Time) >= frm && DbFunctions.TruncateTime(x.Feed_Time) <= todat))
.ToList().GroupBy(r => r.Pond_Name, (key, enumerable) =>
{
return new feed_fish { Pond_Name = key, Total_feed_weight = enumerable.Sum(k => k.Total_feed_weight) };
}).OrderByDescending(t => t.Total_feed_weight).ToList();
Output
Pond Name: FarmAx_web.feed_fish. Total Feed:
Update: To test the Where clause I just returned it as datasource to a grid and it brought the right results...
var hfeed = db.feed_fish.Where(x => (DbFunctions.TruncateTime(x.Feed_Time) >= frm && DbFunctions.TruncateTime(x.Feed_Time) <= todat)).ToList();
fishwtaveragegrid.DataSource = hfeed;
fishwtaveragegrid.DataBind();