如何在没有硬编码列的情况下在LINQ中透视数据

时间:2016-05-16 09:17:07

标签: c# linq datatable pivot

我有sql server这样的表

CodeItemsRule Table 
CodeID  ItemID RuleID 
00009   D1      2   
00009   D2      2
00009   D3      1
00008   D1      3
00007   D3      1
00007   D4      1
00010   D3      2
00010   D1      1
00010   D2      1

我需要像这样在LINQ中转移这些数据。

CodeID  D1 D2 D3 D4 D5 D6 D7 D8 D9 D10 D11 D12 D13 D14
00007          1  1
00009   2   2  1

下面给出的是我的代码,但它不会将其转换为数据透视格式。

List<CodeItemsRule> _CodeItemRules = new CodeItemsRuleRepository.GetAll();
var _GroupResult = _CodeItemRules.GroupBy(g => g.CodeID).Select(g => new 
{
    CodeID = g.Key,
    ItemRulesList = g.ToDictionary(t => t.ItemID, t => t.RuleID)
}).ToList()

1 个答案:

答案 0 :(得分:2)

我通过修改the link的详细信息为您简化了解决方案。

首先在静态类中创建扩展方法// work repository public function findByKeyword($keyword) { $qb = $this->createQueryBuilder("w"); $result = $qb ->add('where', $qb->expr()->like("wc.name", ':keyword')) ->leftjoin("w.client", "wc") //or join or innerjoin depends of your case ->setParameters([ 'keyword' => $keyword ]) ->getQuery() ->getResult() ; return $result; }

ToPivotTable

然后,在列表中使用此扩展方法获取您的透视public static class PivotClass { public static DataTable ToPivotTable<T, TColumn, TRow, TData>(this IEnumerable<T> source, Func<T, TColumn> columnSelector, Expression<Func<T, TRow>> rowSelector, Func<IEnumerable<T>, TData> dataSelector) { DataTable table = new DataTable(); var rowName = ((MemberExpression)rowSelector.Body).Member.Name; table.Columns.Add(new DataColumn(rowName)); var columns = source.Select(columnSelector).Distinct(); foreach (var column in columns) table.Columns.Add(new DataColumn(column.ToString())); var rows = source.GroupBy(rowSelector.Compile()) .Select(rowGroup => new { Key = rowGroup.Key, Values = columns.GroupJoin( rowGroup, c => c, r => columnSelector(r), (c, columnGroup) => dataSelector(columnGroup)) }); foreach (var row in rows) { var dataRow = table.NewRow(); var items = row.Values.Cast<object>().ToList(); items.Insert(0, row.Key); dataRow.ItemArray = items.ToArray(); table.Rows.Add(dataRow); } return table; } } ,如下所述:

DataTable