class数据添加会重写已经存在的数据
class data add will rewrite the data already exists
我有一个 class 并且在 2 个 foreach 循环中我想将我数据集中 table 中的所有数据添加到我的 class 但问题是:在它之后完成内部 foreach 循环,下一个要复制的 table 也将替换 ret
中已有的记录所以最后如果我有 2 tables of table 1 行中的 1 行和 table 2 行中的 2 我将在 ret
中有 3 条记录,但是 table 1 中的所有数据都替换为 table2 中的数据!
例子
table 1 table 2
------ ----------
呜呜呜
-- -- -- --
测试 mm dd
抄送
但最后在 ret 而不是 {te st}{mm dd}{ss cc} 我有 {mm dd}{mm dd}{ss cc} 我有
帮助!
list<class> ret = new list<class>();
class FR = new class();
foreach (DataTable table in ds.Tables)
{
foreach (DataRow row in table.Rows)
{
if (String.IsNullOrEmpty(FR.v) || FR.v != row["v"])
{
FR.v = row["v"].ToString();
}
if (String.IsNullOrEmpty(FR.y) || FR.y != row["y"])
{
FR.y = row["y"].ToString();
}
ret.Add(FR);
}
}
FR
始终是同一个实例,因此每次在其上设置值时,您都是在同一个实例上操作并一遍又一遍地将其重新添加到集合中。
只需在循环的每次迭代中创建一个新实例:
List<SomeClass> ret = new List<SomeClass>();
foreach (DataTable table in ds.Tables)
{
foreach (DataRow row in table.Rows)
{
SomeClass FR = new SomeClass(); // <--- right here
if (String.IsNullOrEmpty(FR.v) || FR.v != row["v"])
{
FR.v = row["v"].ToString();
}
if (String.IsNullOrEmpty(FR.y) || FR.y != row["y"])
{
FR.y = row["y"].ToString();
}
ret.Add(FR);
}
}
我有一个 class 并且在 2 个 foreach 循环中我想将我数据集中 table 中的所有数据添加到我的 class 但问题是:在它之后完成内部 foreach 循环,下一个要复制的 table 也将替换 ret
中已有的记录所以最后如果我有 2 tables of table 1 行中的 1 行和 table 2 行中的 2 我将在 ret
中有 3 条记录,但是 table 1 中的所有数据都替换为 table2 中的数据!
例子
table 1 table 2 ------ ---------- 呜呜呜 -- -- -- -- 测试 mm dd 抄送
但最后在 ret 而不是 {te st}{mm dd}{ss cc} 我有 {mm dd}{mm dd}{ss cc} 我有 帮助!
list<class> ret = new list<class>();
class FR = new class();
foreach (DataTable table in ds.Tables)
{
foreach (DataRow row in table.Rows)
{
if (String.IsNullOrEmpty(FR.v) || FR.v != row["v"])
{
FR.v = row["v"].ToString();
}
if (String.IsNullOrEmpty(FR.y) || FR.y != row["y"])
{
FR.y = row["y"].ToString();
}
ret.Add(FR);
}
}
FR
始终是同一个实例,因此每次在其上设置值时,您都是在同一个实例上操作并一遍又一遍地将其重新添加到集合中。
只需在循环的每次迭代中创建一个新实例:
List<SomeClass> ret = new List<SomeClass>();
foreach (DataTable table in ds.Tables)
{
foreach (DataRow row in table.Rows)
{
SomeClass FR = new SomeClass(); // <--- right here
if (String.IsNullOrEmpty(FR.v) || FR.v != row["v"])
{
FR.v = row["v"].ToString();
}
if (String.IsNullOrEmpty(FR.y) || FR.y != row["y"])
{
FR.y = row["y"].ToString();
}
ret.Add(FR);
}
}