我已通過修改the link的詳細信息爲您簡化了解決方案。
首先在靜態類中創建一個擴展方法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
如下所述:
List<CodeItemsRule> _CodeItemRules = new List<CodeItemsRule>()
{
new CodeItemsRule()
{
CodeID="00009",
ItemID="D1",
RuleID=2
},new CodeItemsRule()
{
CodeID="00009",
ItemID="D2",
RuleID=2
},new CodeItemsRule()
{
CodeID="00009",
ItemID="D3",
RuleID=1
},new CodeItemsRule()
{
CodeID="00008",
ItemID="D1",
RuleID=3
},new CodeItemsRule()
{
CodeID="00007",
ItemID="D3",
RuleID=1
},new CodeItemsRule()
{
CodeID="00007",
ItemID="D4",
RuleID=1
},new CodeItemsRule()
{
CodeID="00010",
ItemID="D3",
RuleID=2
},new CodeItemsRule()
{
CodeID="00010",
ItemID="D1",
RuleID=1
},new CodeItemsRule()
{
CodeID="00010",
ItemID="D2",
RuleID=1
}
};
var pivotTable = _CodeItemRules.ToPivotTable(
item => item.ItemID,
item => item.CodeID,
items => items.Any() ? items.Sum(x => x.RuleID) : 0);
「*但這只是一半的工作*「另一半是什麼?轉換爲'DataTable'?這不是LINQ任務。 –
@Ivan Stoev其實我的linq代碼不會將數據轉換爲數據透視格式,我需要將其轉換爲透視格式,我修改了我的問題。 – 3355307
嘗試在http://techbrij.com/pivot-c-array-datatable-convert-column-to-row-linq中提供的解決方案1 – Sarathy