1

我有下面的代码。如果RecoveryRecords变量中的数据不在 ValidClaimControl 编号中,我将根据以下条件删除它。

RecoveryRecords.Remove(s)执行该行后,它也将从记录变量中删除。我实际上需要来自记录变量的数据。

我想知道如何在记录变量中保留数据?

List<List<Field>> records = new List<List<Field>>();
List<List<Field>> RecoveryRecords = new List<List<Field>>();

//Some Logic here to populate records variable

RecoveryRecords = records;
List<string> validClaimControlNo = new List<string>();

//Some Logic here to populate validClaimControlNo variable

foreach (List<Field> s in RecoveryRecords.ToList())
{
    foreach (Field f in s)
    {
        if (!(validClaimControlNo.Contains(f.Value)))
          RecoveryRecords.Remove(s);
    }
}
4

6 回答 6

6

这条线不符合你的想法,我怀疑:

RecoveryRecords = records;

它只是将 的值(对对象records引用)复制为 的新值RecoveryRecords。这两个变量引用同一个对象。如果您想要一个包含来自 的数据副本的新列表records,您需要明确地执行此操作,例如

RecoveryRecords = new List<List<Field>>(records);

或者

RecoveryRecords = records.ToList();

请注意,即使这也只是列表的浅表副本 - 如果您写道:

RecoveryRecords[0].Add(new Field());

该更改也将在其中可见records[0],因为它们都将引用相同的List<Field>.

于 2012-10-05T18:50:26.240 回答
5

通过将元素枚举到新列表中

RecoveryRecords = records.ToList();

(就像你在 foreach 循环中说的那样RecoveryRecords.ToList()

于 2012-10-05T18:49:50.907 回答
2

替换这两行:

List<List<Field>> records = new List<List<Field>>();
List<List<Field>> RecoveryRecords = new List<List<Field>>(records);

并删除此行:

RecoveryRecords = records;
于 2012-10-05T18:50:59.303 回答
1

这就是为什么:

RecoveryRecords = records;

你没有两个变量指向不同的列表,你有两个变量指向同一个列表。

制作列表的副本:

RecoveryRecords = new List<List<Field>>(records);

注意:现在您有两个单独的列表,但您应该知道列表中的List<Field>项目在两个列表中是相同的。

于 2012-10-05T18:51:40.363 回答
1

使用这条线:

RecoveryRecords = records;

您正在传递recordsto RecoveryRecords( reference ) 的指针,这意味着records列表中的每个更改都在RecoveryRecords. 因此,您应该克隆列表,并且可以使用以下代码执行此操作:

RecoveryRecords = new List<List<Field>>(records);
于 2012-10-05T18:52:45.040 回答
0

您正在使用这行代码浅复制您的记录对象

RecoveryRecords = records;

你需要做一个深拷贝

RecoveryRecords = new List<List<Field>>(records);

这是许多编程语言的共同主题。维基百科很好地解释了它,http ://en.wikipedia.org/wiki/Object_copy 。

于 2012-10-05T18:56:21.567 回答