List<>からクロス集計表(ピポットテーブル)を作成してListViewとして表示する
// 成績結果リストの作成
var scoreResults = new List<ScoreResult>
{
new ScoreResult { Name = "直美", Subject = "国語", Score = 65 },
new ScoreResult { Name = "直美", Subject = "算数", Score = 70 },
new ScoreResult { Name = "直美", Subject = "算数", Score = 5 },//算数 75
new ScoreResult { Name = "慶子", Subject = "国語", Score = 80 },
new ScoreResult { Name = "慶子", Subject = "算数", Score = 85 },
new ScoreResult { Name = "慶子", Subject = "社会", Score = 90 },
new ScoreResult { Name = "沙織", Subject = "算数", Score = 60 },
new ScoreResult { Name = "沙織", Subject = "社会", Score = 55 },
new ScoreResult { Name = "沙織", Subject = "社会", Score = 10 }//社会 65
};
// 成績結果リストから科目の一覧を取得
var subjects = scoreResults.Select(s => s.Subject).Distinct().ToList();
var pivotTable = scoreResults
.GroupBy(s => s.Name)
.Select(g =>
{
dynamic expando = new ExpandoObject();
expando.Name = g.Key;
var Result = (IDictionary<string, object>)expando;
// 科目ごとの合計点を計算
foreach (var subject in subjects)
{
//科目のプロパティを作成
Result[subject] = g.Where(s => s.Subject == subject).Sum(s => s.Score);
}
return expando;
});
// Create ListView
var listView = new ListView();
// Create GridView
var gridView = new GridView();
// Add columns to GridView
gridView.Columns.Add(new GridViewColumn { Header = "Name", DisplayMemberBinding = new Binding("Name") });
// 科目のプロパティColumnを追加
foreach (var subject in subjects)
{
gridView.Columns.Add(new GridViewColumn { Header = subject, DisplayMemberBinding = new Binding(subject) });
}
// Set GridView as ListView's View
listView.View = gridView;
// Add items to ListView
foreach (var row in pivotTable)
{
var expandoDict = (IDictionary<string, object>)row;
var item = new ListViewItem();
item.Content = row;
listView.Items.Add(item);
}
// Add ListView to the main window
this.Content = listView;