Fredi Tansari
Fredi Tansari

Reputation: 95

how to sum and group data in linq

Here's a table that i have:enter image description here

anyway what I wanted to do in linq is to sum feedGiven column with a group by logdate (we can truncate the time.. it's not needed) with the productionCycleID.

And then take the last 7 Days sum of feed given and average it out.

Currently here's what I got for now:

 public IQueryable<FeedingLog> getLastSevenDaysAverage(int intendedProductionCycleID)
    {
        var ListProductionCycleQuery = this.ObjectContext.FeedingLogs.Where(b => b.ProductionCycleID== intendedProductionCycleID);

        var SumResult = from s in ListProductionCycleQuery
                        group s by new {s.ProductionCycleID,s.feedGiven, s.LogDate} into g
                        select new {g.Key.ProductionCycleID, g.Key.LogDate g.Sum(y => y.feedGiven)};

        return ListProductionCycleQuery;
    }

I'm seriously stumped by linq, Normally i would do it in sql, but entity framework is a little bit buggy if I go with a view (no primary key issue)

I'm also having this issue in the code :

enter image description here

basically it says invalid anonymous type member declarator. anonymous type memmer must be declared with a member assignment. Thanks in advance for reading and solutions

Upvotes: 0

Views: 200

Answers (2)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

Omit the GroupBy-clause for feedGiven:

var SumResult = from s in ListProductionCycleQuery
    group s by new {s.ProductionCycleID,s.LogDate} into g
    select new {g.Key.ProductionCycleID, g.Key.LogDate g.Sum(y => y.feedGiven)};

Upvotes: 0

Jamiec
Jamiec

Reputation: 136104

You've included feedGiven in the group by, however this is the one field you don't want as part of the grouping

var SumResult = from s in ListProductionCycleQuery
                group s by new {s.ProductionCycleID,s.LogDate} into g
                select new {g.Key.ProductionCycleID, g.Key.LogDate g.Sum(y => y.feedGiven)};

In addition, you're returning the original query from the function, you want to probably define a class to represent the grouped/summed info and return that.

Upvotes: 1

Related Questions