[英]how to create a pivot table with dynamic column using linq tree expression
我正在寫一個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()
});
我將舉例說明' table1
'的外觀以及' table2
'的外觀如何:
任何人都可以幫我找到一個解決方案,使用linq樹表達式或其他linq方法創建一個動態列的數據透視表; 任何幫助將非常感激。
無法在sql
查詢動態數量的列。 通過擴展,不可能使用linq,因為它基於sql。
所以你運氣不好,抱歉。
但是,您可以從sql
server請求所有現有的{country, product}
對,並在客戶端上執行剩余的處理(通過執行.Select(x => x.product).Distinct()
等來重建國家和產品,以及然后在數據網格中動態創建列。
我一直在使用此擴展名來轉動列表。
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;
}
希望這有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.