C# Linq Group by to列

C# Linq Group by to列,c#,linq,C#,Linq,我有一个带有属性code的项目列表,我想按eventId分组,并创建一个表表示形式,其中代码值转换为列。 每个三元组(事件、代码、金额)都是唯一的 我想改变这个 eventId code amount 1 A 100 1 B 101 1 C 102 2 A 103 2 C 104 3 B 105 .... 对此 eventId A B C

我有一个带有属性code的项目列表,我想按eventId分组,并创建一个表表示形式,其中代码值转换为列。 每个三元组(事件、代码、金额)都是唯一的

我想改变这个

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

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,
              ....
           }

您需要对分组结果进行筛选,并将其投影到匿名对象:

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)
           }

您需要对分组结果进行筛选,并将其投影到匿名对象:

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)
           }

实际上,使用查找非常方便:

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(),
    };
我得到这个结果:


实际上,使用查找非常方便:

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(),
    };
我得到这个结果:


谢谢,我从一开始就不知道代码。你需要在
代码上分组,然后选择里面的内容(无需显示总和,每个三元组都是唯一的)。?我将更新我的帖子,展示你如何做到这一点。看一看:谢谢,我从一开始就不知道代码您需要在
code
上分组,然后选择内部的内容(无需显示总和,每个三元组都是唯一的)。?我将更新我的帖子,展示您如何做到这一点。请看: