2011-02-08 136 views
5

我正在寫一個asp.net C# Web應用程序來創建動態列數據透視表; 我有命名爲「table1」具有三列「country」,「productId」和「productQuantity」的內存中的數據表; 我想旋轉該表以獲取具有第一列'country'作爲固定列和動態數字以及列名'product_1','product_2',...的新表(假設'table2')...根據'table1'中存在的產品總數,'product_n'; 第一列'country'必須包含國家名稱; 動態生成列「product_1」,「product_2」,......,「product_n」必須包含已在指定的國家如何使用LINQ樹表達

被selled爲每個特定的產品,我使用LINQ查詢表達式寫的productQuantity碼;問題是我不能硬編碼這些名字,也沒有這些產品的價值;我無法預測數據表中存在多少產品; 現在,我使用下面的表達式正在測試的結果:

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」必須是這樣的:

view example image of the two tables table1 and table2

誰能幫我找到了使用LINQ表達式樹或其他LINQ方法創建具有動態列數據透視表的解決方案; 任何幫助將不勝感激。

+0

等待任何幫助... – user598956 2011-02-08 03:00:49

回答

0

我一直在使用這個擴展旋轉列表。

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; 
    } 

希望得到這個幫助。

+0

感謝您的回覆,但它不適用於我的情況。 – user598956 2011-02-08 04:45:41

2

無法查詢sql中的動態列數。通過擴展,不可能用linq做到這一點,因爲它基於sql。

所以你是不走運的,對不起。

但是你可以請求{country, product}所有現有的對從sql服務器,並做客戶端上的剩餘處理(做.Select(x => x.product).Distinct()等重建國家和產品,然後動態地在DataGrid中創建列)。