【问题标题】:how to create a pivot table with dynamic column using linq tree expression如何使用 linq 树表达式创建具有动态列的数据透视表
【发布时间】:2015-03-30 14:59:21
【问题描述】:

我正在编写一个 asp.net C# 网络应用程序; 我有一个名为“table1”的内存数据表,它有三列“country”、“productId”和“productQuantity”; 我想旋转该表以获得一个新表(假设'table2'),其中第一列'country'作为固定列以及列的动态编号和名称'product_1','@ 987654330@', ..., '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”的外观:

view example image of the two tables table1 and table2

谁能帮我找到使用 linq 树表达式或其他 linq 方法创建具有动态列的数据透视表的解决方案; 任何帮助将不胜感激。

【问题讨论】:

  • 等待任何帮助...

标签: c# asp.net linq linq-to-dataset over-clause


【解决方案1】:

无法查询sql 中的动态列数。通过扩展,使用 linq 也无法做到这一点,因为它基于 sql。

所以你运气不好,对不起。

但是,您可以从sql 服务器请求所有现有的{country, product} 对并在客户端进行剩余处理(通过执行.Select(x => x.product).Distinct() 等来重建国家和产品,然后在数据网格中动态创建列) .

【讨论】:

    【解决方案2】:

    我一直在使用这个扩展来旋转列表。

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

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2018-11-16
      • 1970-01-01
      • 2016-02-28
      • 1970-01-01
      • 2019-11-07
      • 2019-12-22
      • 2022-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多