C# linq中的数据透视
我有一个数据集,它返回我这组结果:C# linq中的数据透视,c#,linq,pivot,pivot-without-aggregate,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
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”子句(例如:ifdate==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
});
}
然后,数据透视位置列表应包含数据透视形式的数据,如您所需。尝试以下操作:
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
});
}
然后,PivotedLocations
列表应包含数据透视形式的数据,如您所需。请参阅尝试可能的重复请参阅尝试可能的重复