c# - linq 中的数据透视表

标签 c# linq pivot pivot-without-aggregate

我有一个数据集可以返回这组结果:

Date      |Location |Amount
11.03.2011|Location1|  1000  
11.03.2011|Location2|  1000  
11.03.2011|Location3|  1000  
12.03.2011|Location1|  1000    
12.03.2011|Location2|  1000    
12.03.2011|Location3|  1000  
13.03.2011|Location4|  1000 

我需要这样安排我的数据:

Location | 11.03.2011|12.03.2011|13.03.2011|    
Location1|       1000|      1000|         0|  
Location2|       1000|      1000|         0|  
Location3|       1000|      1000|         0|  
Location4|          0|         0|      1000|  

请注意:我不知道行中的日期,所以我无法使用“if”子句(例如:if date == DateTime.Parse(11.03.2011) ).

我希望我的解释是清楚的。

最佳答案

试试这个:

var Locations = Data.GroupBy(l => l.Location);
                .SelectMany( g => 
                             new 
                             { 
                                 LocationName = g.Key, 
                                 Amounts = g 
                             });

Func<Location, bool> matchMonth11 = l => l.Date == "11.03.2011";
Func<Location, bool> matchMonth12 = l => l.Date == "12.03.2011";
Func<Location, bool> matchMonth13 = l => l.Date == "13.03.2011";

var PivotedLocations = new List<PivotedLocation>();

foreach(var item in Locations )
{
    PivotedLocations.Add( new PivotedLocation
                          {
                              LocationName  = item.LocationName,
                              month11Amount = item.Amounts.Where(matchMonth11)
                                              .FirstOrDefault().Amount,
                              month12Amount = item.Amounts.Where(matchMonth12)
                                              .FirstOrDefault().Amount,
                              month13Amount = item.Amounts.Where(matchMonth13)
                                              .FirstOrDefault().Amount
                          });

}

您应该首先定义以下类:

public class PivotedLocation
{
    public string LocationName { get; set; }
    public int month11Amount { get; set; }
    public int month12Amount { get; set; }
    public int month13Amount { get; set; }
}

然后 PivotedLocations 列表应该包含您想要的旋转形式的数据。

关于c# - linq 中的数据透视表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6098555/

相关文章:

sql - T-SQL 枢轴 : One row to column name and the other to value

python - Pandas 数据透视表 - 通过合并列的划分创建附加列

c# - UWP : How to resize an Image

c# - 为什么编译器不能确定这个 lambda 是一个 Delegate?

c# - 我的应用程序占用的内存随着时间的推移不断增加

c# - 如何从 linq 查询结果中忽略/删除非数字值 C#

c# - System.Web.Mvc.HtmlHelper 不包含 'DropDownListFor' 的定义

c# - 如何使用 LINQ to Objects 安排作业而不重叠?

c# - 正则表达式 - 改进搜索并添加第三组

sql-server - 带有计数和总和的 SQL Server 数据透视表