0

I have a list of items with a property code and I want to group by eventId and create a table representation where code values are transformed to columns. Every triple (event, code,amount) is unique.

I want to transform this

eventId code  amount  
  1      A     100
  1      B     101
  1      C     102
  2      A     103
  2      C     104
  3      B     105
  ....

to this

eventId  A    B   C
 1      100  101 102
 2      103   0  104
 3       0   105  0
 ... 


var table=from x in list
    group x by x.eventId into gr
    select new
           {
              eventId=gr.Key,
              ....
           }
albert
  • 1,493
  • 1
  • 15
  • 33

2 Answers2

2

You need to filter on grouped result and project in to anonymous object :

var table=from x in list
    group x by x.eventId into gr
    select new
           {
              eventId=gr.Key,
              A = gr.Where(x=>x.code == "A").Sum(x=>x.amount),
              B = gr.Where(x=>x.code == "B").Sum(x=>x.amount),
              C = gr.Where(x=>x.code == "C").Sum(x=>x.amount)
           }
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
0

It's actually quite neat to use a lookup:

var table =
    from x in list
    group x by x.eventId into gr
    let lookup = gr.ToLookup(y => y.code, y => y.amount)
    select new
    {
        eventId = gr.Key,
        A = lookup["A"].Sum(),
        B = lookup["B"].Sum(),
        C = lookup["C"].Sum(),
    };

I get this result:

query

Enigmativity
  • 113,464
  • 11
  • 89
  • 172