私はこのようなデータテーブルを持っています:
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]
コメントを追加