2011-02-08 131 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中创建列)。