我有这样的数据..
ID
1234-001
1234-002
1234-003
5678-001
7890-001
7890-002
我将此数据保存在数据表中。我正在尝试根据基数(即 1234、5678、7890)对行进行一些处理
如何迭代此数据表并保存新的(临时)数据表
1234-001,1234-002, 1234-003
clear the temp datatable then hold
5678-001
clear the temp datatable then hold
7890-001,7890-002
我正在处理旧代码库,LINQ 不可用。我想不出一个优雅的解决方案。也许与数据 View 有关,我不确定?
最佳答案
你说你不想使用 LINQ,但更喜欢一个优雅的解决方案...除非我在你的问题中遗漏了一些重要的东西,否则这个 LINQified 代码似乎可以让你做你想做的事。
var grouped = from d in data
group d by d.Id.Split('-').FirstOrDefault();
foreach(var g in grouped) {
// do something with each group
}
非 LINQ、非 var 答案:
DataTable data = new DataTable();
data.Columns.Add("ID");
data.Columns.Add("Value");
data.Rows.Add("1234-001", "Row 1");
data.Rows.Add("1234-002", "Row 2");
data.Rows.Add("1234-003", "Row 3");
data.Rows.Add("5678-001", "Row 4");
data.Rows.Add("7890-001", "Row 5");
data.Rows.Add("7890-002", "Row 5");
Dictionary<String, List<DataRow>> grouped = new Dictionary<String, List<DataRow>>();
foreach(DataRow r in data.Select()) {
List<DataRow> groupedRows;
String key = r["ID"].ToString().Split('-')[0];
if(!grouped.TryGetValue(key, out groupedRows)) {
groupedRows = new List<DataRow>();
grouped[key] = groupedRows;
}
groupedRows.Add(r);
}
foreach(KeyValuePair<String, List<DataRow>> g in grouped) {
String groupKey = g.Key;
Console.WriteLine(groupKey);
foreach(DataRow r in g.Value) {
Console.WriteLine("\t{0}", r["Value"]);
}
}
我得到以下输出,所以我没有看到“它只对前 3 个进行分组并停止”:
1234
Row 1
Row 2
Row 3
5678
Row 4
7890
Row 5
Row 5
关于c# - 对数据表中的行进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23962519/