我已成功使用此示例代码。
public static Dictionary<TKey1, Dictionary<TKey2, TValue>> PivotLinq<TSource, TKey1, TKey2, TValue>(
this IEnumerable<TSource> source, Func<TSource, TKey1> key1Selector, Func<TSource, TKey2> key2Selector,
Func<IEnumerable<TSource>, TValue> aggregate)
{
return source.GroupBy(key1Selector).Select(
x => new
{
X = x.Key,
Y = x.GroupBy(key2Selector).Select(
z => new
{
Z = z.Key,
V = aggregate(z)
}
).ToDictionary(e => e.Z, o => o.V)
}
).ToDictionary(e => e.X, o => o.Y);
}
现在我已将其扩展如下:
public static Dictionary<TKey1, Dictionary<TKey2,Dictionary<TKey3,Dictionary<TKey4,TValue>>>> PivotLinq<TSource, TKey1, TKey2,TKey3,TKey4, TValue>(
this IEnumerable<TSource> source, Func<TSource, TKey1> key1Selector, Func<TSource, TKey2> key2Selector, Func<TSource, TKey3> key3Selector, Func<TSource, TKey4> key4Selector,
Func<IEnumerable<TSource>, TValue> aggregate)
{
return source.GroupBy(key1Selector).Select(
x => new
{
X = x.Key,
Y = x.GroupBy(key2Selector).Select(
z => new
{
Z = z.Key,
V =z.GroupBy(key3Selector).Select( // aggregate(z)
w => new
{
W=w.Key ,
B = w.GroupBy(key4Selector).Select(
c=> new
{
C=c.Key ,
D=aggregate(c)
}).ToDictionary(e=>e.C, o=>o.D)
}
).ToDictionary(e=>e.W, o=>o.B)
}
).ToDictionary(e=>e.Z , o=>o.V )
}).ToDictionary(e=>e.X,o=>o.Y);
}
但是,聚合函数不会产生所需的结果。有人能让我知道我哪里出错吗?