我有一个这样的数据表:
name | color of name
----------------------
x | red
y | blue
z | yellow
x | yellow
y | red
我需要像这样获得这张表的枢轴:
name | red | blue | yellow | total
-------------------------------------------------------
x | 1 | 0 | 1 | 2
y | 1 | 1 | 0 | 2
z | 0 | 0 | 1 | 1
如何在 VB.NET 中使用 Linq 执行此操作?
颜色不是动态的。我可以将它们放在硬编码中的查询中。
所以我需要按名称和列中记录颜色的总和对所有记录进行分组。然后是总颜色的总和(如果你帮助第一个,我可以计算总数:p)
我创建了我的DataTable
枢轴扩展方法的变体,该方法根据列的存在创建交集值并添加总计列。
public static class DataTableExt {
public static DataTable PivotByOverWithTotal(this DataTable dt, string ByRowFieldName, string OverColFieldName) {
var res = new DataTable();
if (dt.Rows.Count > 0) {
var dtg = dt.AsEnumerable().GroupBy(r => r[ByRowFieldName], r => r[OverColFieldName].ToString());
res.Columns.Add(ByRowFieldName, dt.Columns[ByRowFieldName].DataType);
var colNames = dtg.SelectMany(rg => rg).Distinct().OrderBy(n => n);
foreach (var n in colNames)
res.Columns.Add(n, typeof(int));
res.Columns.Add("Total", typeof(int));
foreach (var rg in dtg) {
var newr = res.NewRow();
newr[ByRowFieldName] = rg.Key;
int total = 0;
foreach (var rv in colNames) {
var val = rg.Contains(rv) ? 1 : 0;
newr[rv] = val;
total += val;
}
newr["Total"] = total;
res.Rows.Add(newr);
}
}
return res;
}
}
你像这样使用它:
var ansdt = src.PivotByOverWithTotal("name", "color");
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句