【发布时间】:2016-04-16 07:59:24
【问题描述】:
我确实有另一个问题,我认为我在路上做得很好,只是意识到字典很有用,但我需要能够真正使用我的 Datatable 来循环。
字典正确显示数据,但我对已编辑数据表的循环清楚地显示了已编辑数据和旧数据
https://dotnetfiddle.net/6BzsYh
DataTable table1 = new DataTable();
table1.Columns.Add("ID", typeof (int));
table1.Columns.Add("Weight", typeof (int));
table1.Columns.Add("Name", typeof (string));
table1.Columns.Add("Breed", typeof (string));
table1.Rows.Add(23, 57, "Koko", string.Empty);
table1.Rows.Add(44, 130, "Fido", null);
table1.Rows.Add(54, 130, "Jack", null);
table1.Rows.Add(44, 130, "Thad", null);
table1.Rows.Add(64, 130, "John", null);
table1.Rows.Add(23, 130, "Brian", null);
table1.Rows.Add(445, 130, "James", null);
table1.Rows.Add(64, 134, "Adam", null);
Dictionary<int, string> dict = new Dictionary<int, string>();
for (int i = 0; i < table1.Rows.Count; i++)
{
int id = Convert.ToInt32(table1.Rows[i][0]);
if (dict.ContainsKey(id))
{
//comma separate the Names
dict[id] += ", " + table1.Rows[i][2].ToString();
// change the Name value in the table
table1.Rows[i][2] = dict[id];
//Console.WriteLine(dict[id]);
}
else
{
dict.Add(id, table1.Rows[i][2].ToString());
}
//Console.WriteLine()
}
foreach (DataRow eaRow in table1.Rows)
{
Console.WriteLine("ID=" + eaRow[0] + " Name=" + eaRow[2]);
}
Console.WriteLine("\n\n");
//dictionary is correct
foreach (var item in dict)
{
Console.WriteLine("ID=" + item.Key + " Name=" + item.Value);
}
【问题讨论】:
-
嗯,是的。你没有做任何事情来从 table1 中删除重复的行,所以它们当然仍然存在。
-
如何合并 2 行?我想通过创建单行来替换那些现有的行
-
您是否正在寻找一种方法来检查数据表中的重复值..?如果是这样,有办法做到这一点,我可以发布一个示例供您测试,您可以从那里获取它也可以问很多问题,例如
How do I,当您可以谷歌时 -
您的最终目标到底是什么?有一个包含“合并”数据的 DataTable?
-
最终目标是最终在上面循环遍历将重复行与各种特定列组合但基于 ID 的数据表(真实数据就像 30 列,所以我试图用 jsfiddle 显示表示)
标签: c# .net dictionary datatable datarow