简体   繁体   中英

Linq Query using GroupBy() and Sum() and Returning Values not Grouped

When attempting to write a linq query to Group some Data and Sum it, i'm receiving the following error:

CS1061 'CM_Records' does not contain a definition for 'Sum' and no extension method 'Sum' accepting a first argument of type 'CM_Records' could be found

var results = (from r in CM_Records
      join sub in CM_Records on r.Id equals sub.Id
      select new {R = r, S = sub}
      into joined
      group joined by new
      {
         label = joined.R.ServiceDateTime.Value.Month + "/" + joined.R.ServiceDateTime.Value.Day + "/" + joined.R.ServiceDateTime.Value.Year,
         joined.R.CategoryId
      }
      into grouped
      select grouped.Select(g =>
         new
         {
            grouped.Key.label,
            grouped.Key.CategoryId,
            Value = g.S.Sum(x => int32.Parse(x.Value)), //This is the line that fails
            //Value = g.S.Value, //Uncomment this line and comment the line above to get the following output.
            ServiceTime = Convert.ToDateTime(g.S.ServiceDateTime).ToShortTimeString()
         })
   )
   .SelectMany(x => x);

I understand that Sum Requires the object to be IQueryable , just not sure how to accomplish that in this this query without breaking something else. Keep in mind that this query is being set to variable and then used in conjunction to generate a JSON object in C#.

Current Output without SUM:

Label    Cat.  Value ServiceTime
1/1/2017    439960  121 9:00 AM
1/1/2017    439960  131 5:00 PM
1/1/2017    439960  213 11:45 AM
1/1/2017    439960  210 10:20 AM
1/1/2017    439961  143 9:30 AM
1/1/2017    439994  92  9:30 AM
1/1/2019    439989  0   7:00 PM
1/1/2020    439968  172 7:00 PM
1/10/2018   439968  124 7:00 PM
1/10/2018   439969  120 7:00 PM

I need the above results to be Grouped by the Label Column and the Values summed.

Try this query:

var results = (from r in CM_Records
               join sub in CM_Records on r.Id equals sub.Id
               select new {R = r, S = sub}
               into joined
               group joined by new
               {
                  label = joined.R.ServiceDateTime.Value.Month + "/" + joined.R.ServiceDateTime.Value.Day + "/" + joined.R.ServiceDateTime.Value.Year,
                  joined.R.CategoryId
               }
               into grouped
               select new
               {
                  grouped.Key.label,
                  grouped.Key.CategoryId,
                  Value = grouped.ToList().Select(x => x.S.value).Sum()
               }).ToList();

Including the ServiceTime doesn't make much sense, unless you decide to select the max, min or something like that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM