我有一个数据集,它返回了这组结果:
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
列表应包含所需的透视形式的数据。