use*_*956 5 c# linq asp.net linq-to-dataset over-clause
我正在写一个asp.net C#Web应用程序; 我有一个名为' table1'有三列' country',' productId'和' productQuantity' 的内存数据表; 我想转动该表以获得一个新表(假设' table2')将第一列' country'作为固定列,动态数字和列' product_1',' product_2',...,' product_n'的名称根据' table1'中存在的产品总数; 第一列' country'必须包含国家/地区名称; 动态生成的列' product_1',' product_2',...,' product_n'必须包含productQuantity已为指定国家/地区的每个特定产品选择的列
我正在使用Linq查询表达式来编写代码; 问题是我不能硬编码名称和产品的价值; 我无法预测数据表中存在多少产品; 现在,我正在使用以下表达式测试结果:
var query = table1.AsEnumerable()
.GroupBy(c => c.country)
.Select(g => new
{
country = g.Key,
product_1 = g.Where(c => c.productId == "a30-m").Select(c => c.productQuantity).FirstOrDefault(),
product_2 = g.Where(c => c.productId == "q29-s").Select(c => c.productQuantity).FirstOrDefault(),
.
.
.
product_n = g.Where(c => c.productId == "g33-r").Select(c => c.productQuantity).FirstOrDefault()
});
Run Code Online (Sandbox Code Playgroud)
我将举例说明' table1'看起来如何以及如何' table2看起来像:
谁能帮助我找到一个解决方案,使用linq树表达式或其他linq方法创建一个带有动态列的数据透视表; 任何帮助将非常感激.
我一直在使用这个扩展来旋转列表。
public static Dictionary<TFirstKey, Dictionary<TSecondKey, TValue>> Pivot<TSource, TFirstKey, TSecondKey, TValue>(this IEnumerable<TSource> source, Func<TSource, TFirstKey> firstKeySelector, Func<TSource, TSecondKey> secondKeySelector, Func<IEnumerable<TSource>, TValue> aggregate)
{
var retVal = new Dictionary<TFirstKey, Dictionary<TSecondKey, TValue>>();
var l = source.ToLookup(firstKeySelector);
foreach (var item in l)
{
var dict = new Dictionary<TSecondKey, TValue>();
retVal.Add(item.Key, dict);
var subdict = item.ToLookup(secondKeySelector);
foreach (var subitem in subdict)
{
dict.Add(subitem.Key, aggregate(subitem));
}
}
return retVal;
}
Run Code Online (Sandbox Code Playgroud)
希望这有帮助。
| 归档时间: |
|
| 查看次数: |
5433 次 |
| 最近记录: |