【问题标题】:How to do a Pivot in Linq [duplicate]如何在 Linq 中进行 Pivot [重复]
【发布时间】:2012-06-19 15:09:31
【问题描述】:

可能重复:
How can i made a pivot for this

我有一张如下所示的表格

 ID     |     value     |    Name
--------+---------------+------------------
  1           Digital        Model
  1           companyA       Manufacturer
  2           Analog         Model
  2           CompanyB       Manufacturer
  3           Fiber          Model
  3           CompanyC       Manufacturer

I need to convert this back to 

 ID     |     Model    |     Manufacturer
--------+--------------+-------------------
 1           Digital          companyA           
 2           Analog           CompanyB        
 3            Fiber           CompanyC       

请帮助我解决这个问题的 Linq 查询。使用 T-SQL,我能够正确转换它。但是,使用 Linq,我发现编写 Query 有问题。

【问题讨论】:

标签: c# linq pivot pivot-without-aggregate


【解决方案1】:

试试这个:

 var results = Data.GroupBy(l => l.Name);
            .SelectMany( g => 
                         new 
                         { 
                             Metadata = g.Key, 
                             data = g 
                         });
var pivoted = new List<PivotedEntity>();

foreach(var item in results)
{
    pivoted.Add( 
        new PivotedEntity
        {
            Id  = item.Id,
            Model = item.data.Where(x => x.Name == "Model")
                        .FirstOrDefault().value,
            Manufacturer = item.data.Where(x => x.Name == "Manufacturer")
                         .FirstOrDefault().value,
        });
}

你应该首先定义一个新的类:

public class PivotedEntity
{
    public int Id {get; set;}
    public string Model {get; set;}
    public string Manufacturer {get; set;}   
}

【讨论】:

  • Mahmoud,谢谢,这很有帮助。
猜你喜欢
  • 2021-10-20
  • 1970-01-01
  • 1970-01-01
  • 2021-09-30
  • 1970-01-01
  • 1970-01-01
  • 2012-10-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多