在LINQ使用数据透视表 [英] Using pivot table in linq

查看:119
本文介绍了在LINQ使用数据透视表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的动态列表



 船员NameSurname期结果
ABC李四Q1 54,09
ABC李四Q2 59,57
ABC李四Q3 62,11

如何我可以在LINQ得到这样的结果与

 船员NameSurname Q1,Q2,Q3 
ABC李四47,51 47, 51 51,46

我尝试过这种方式,但我无法得到的结果。

  List.GroupBy(C => c.PersonnelID)
。选择(G =>新建
{
PersonnelID = g.Key,
= PERIOD1 g.Where(C => c.Period == 1).SUM(C => c.Result),
PERIOD2 = G 。凡(C => c.Period == 2).SUM(C => c.Result),
Period3 = g.Where(C => c.Period == 3).SUM( C => c.Result)
});


解决方案

您可以这样做:

  VAR的结果= Data.GroupBy(L =>新建{l.Crew,l.NameSurname}); 
.SelectMany((键,G)=>

{
机= Key.Crew,
NameSurname = Key.NameSurname,
组= G
});

变种旋转=​​新的List< PivotedCrew>();

的foreach(在结果VAR项)
{
pivoted.Add(
新PivotedCrew
{
机= item.Crew,
NameSurname = item.NameSurname,
Q1 = item.groups.Where。(X => x.Period ==Q1)
.FirstOrDefault()值,
Q2 = item.groups.Where(X => x.Period ==Q2)
.FirstOrDefault()值,
Q3 = item.groups.Where(X =方式> x.Period ==Q3)
.FirstOrDefault()值
})。
}



但你需要定义一个新的类。是这样的:

 公共类PivotedCrew 
{
公共字符串船员标识{搞定;设置;}
公共字符串NameSurname {搞定;设置;}
公共字符串Q1 {搞定;设置;}
公共字符串Q2 {搞定;设置;}
公共字符串Q3 {搞定;设置;}
}


I have the following Dynamic List

Crew   NameSurname  Period  Result
ABC    John DOE     Q1      54,09
ABC    John DOE     Q2      59,57
ABC    John DOE     Q3      62,11

How can I get this result with in linq.

Crew   NameSurname  Q1      Q2      Q3
ABC    John DOE     47,51   47,51   51,46

I've tried this way but I couldn't get the result

List.GroupBy(c => c.PersonnelID)
     .Select(g => new
     {
         PersonnelID = g.Key,
         Period1 = g.Where(c => c.Period == 1).Sum(c => c.Result),
         Period2 = g.Where(c => c.Period == 2).Sum(c => c.Result),
         Period3 = g.Where(c => c.Period == 3).Sum(c => c.Result)
     });

解决方案

You can do this:

var results = Data.GroupBy(l => new { l.Crew, l.NameSurname});
    .SelectMany( (key, g) => 
                 new 
                 { 
                     Crew = Key.Crew,
                     NameSurname = Key.NameSurname,  
                     groups = g 
                 });

var pivoted = new List<PivotedCrew>();

foreach(var item in results)
{
    pivoted.Add( 
        new PivotedCrew
        {
            Crew  = item.Crew,
            NameSurname = item.NameSurname,
            Q1 = item.groups.Where(x => x.Period == "Q1")
                     .FirstOrDefault().value,
            Q2 = item.groups.Where(x => x.Period == "Q2")
                     .FirstOrDefault().value,
            Q3 = item.groups.Where(x => x.Period == "Q3")
                     .FirstOrDefault().value
        });
}

But you will need to define a new class. Something like:

public class PivotedCrew
{
    public string Crew Id {get; set;}
    public string NameSurname {get; set;}
    public string Q1 {get; set;}   
    public string Q2 {get; set;}   
    public string Q3 {get; set;}   
}

这篇关于在LINQ使用数据透视表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆