简体   繁体   中英

Lambda Help Grouping and Summing in C#, need a Func<IGrouping<int, anonymous type, int> or Expression<Func<IGrouping<int, anonymous type>, decimal>>

I'm having a bit of trouble doing an inline .GroupBy() and .Sum() action.

I have a subset of data obtained via a let so it's return type is already anonymous. Hopefully there's enough code in this sample to show what I'm trying to achieve...

from r in Repo.R
  join f in Repo.F
    on f.ID equals r.FFK

let totalB = Repo.B
    .Join(
        b => b.FKID,
        f => f.ID
        (b, f) => new { b.ID, b.Qty, b.Fee })
    .Where(
        b => b.someCriteria == someInput)

group r by new 
   { 
      r.Name,
      TotalFee = totalB
                 .GroupBy(tb => tb.TypeId)
                 .Sum(  /*having trouble here*/ )
   }
into rgroup
select new FinalOutput
   {
        rgroup.Key.Name,
        rgroup.Key.TotalFee
   }

I need a valid:

Func<IGrouping<int, anonymous type>, int> selector

or

Expression<Func<IGrouping<int, anonymous type>, decimal>> selector

看看是否可以编写.Sum(x => x.Key.Fee) ,但是我怀疑整个查询是否可以正常工作或返回预期的结果...

You need to pass the grouping into the Sum selector like this

.Sum(g => ...)

Here "g" is your grouping. It has a key which is the value that it was grouped by, and it also contains all of the values that you grouped. These are values of your anonymous type.

If you call Sum on "g" it'll give you the option of specifying a selector for your anonymous type.

//this is how you can sum values within a grouping
.Sum(g => g.Sum(tb => tb.Fee))

I've guessed "Fee" as the property name in my example, but once you de-reference the "tb" variable your intellisense should kick in and show you the properties available.

I hope this helps :-)

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