將類似 aaa bb 10 cc 11 的多行字符串解析,按首列分組統計後列數值求和,輸出格式化結果。已有 LINQ 字符串版實現,需遷移至 DataTable 場景。
Key(string)、SubKey(string)、Value(int)。DataTable。LINQ to DataSet 分組聚合。DataTable dt = new DataTable();
dt.Columns.Add("Key", typeof(string));
dt.Columns.Add("SubKey", typeof(string));
dt.Columns.Add("Value", typeof(int));
// 假設 data 為原始多行字符串
foreach (var line in data.Split('\n')) {
var parts = line.Split(' ');
for (int i = 1; i < parts.Length; i += 2) {
dt.Rows.Add(parts[0], parts[i], int.Parse(parts[i+1]));
}
}
// LINQ 分組統計
var result = dt.AsEnumerable()
.GroupBy(r => r.Field("Key"))
.Select(g => new {
Key = g.Key,
Count = g.Count(),
SumGroups = g.GroupBy(r => r.Field("SubKey"))
.Select(sg => new { SubKey = sg.Key, Sum = sg.Sum(r => r.Field("Value")) })
});
// 輸出
foreach (var g in result) {
Console.Write($"{g.Key} {g.Count}次 ");
foreach (var sg in g.SumGroups) {
Console.Write($"{sg.SubKey} {sg.Sum} ");
}
Console.WriteLine();
}
var keyCounts = dt.AsEnumerable()
.GroupBy(r => r.Field("Key"))
.Select(g => new { Key = g.Key, Count = g.Count() });
DataTable 內存開銷大,可直接用 List<Tuple<string,string,int>> 替代。AsEnumerable() 需引用 System.Data.DataSetExtensions 程序集。