首页 > 解决方案 > 如何在 C# 中重用列表?

问题描述

我在开始循环之前声明了 aList <T>和 a 。List<List<T>>然后一些元素被添加到List <T>. 在一个条件之后,我List <T>List<List<T>>. 在这一点上我需要,Clear所以List <T>我可以再次使用它,但这也会从 中删除元素List<List<T>>,这是我不希望发生的事情,我该怎么办?

int counter;
List<List<T>> parent= new List<List<T>>();
List<T> child= new List<T>();
for (counter = 0; counter <= group.Count - 2; counter++)
{
    // some code here
    if ( /* condition */ )
    {
        child.Add(element);
        child.Add(element2);
        parent.Add(child);
        child.Clear();
    }
}

注意:我知道其中一种解决方案是new List<T>();在循环内使用,但这不是我的选择。

标签: c#list

解决方案


您不能重复使用子列表。列表是类,因此是引用类型。这意味着您实际上并没有将子列表对象本身存储在父列表中,而是引用您创建的唯一子列表。结果,列表的所有位置都指向同一个唯一的子列表。您必须每次都创建一个新的子列表。

List<List<T>> parent = new List<List<T>>();
for (counter = 0; counter <= group.Count - 2; counter++)
{
    if (condition)
    {
        var child = new List<T>();
        child.Add(element);
        child.Add(element2);
        parent.Add(child);
    }
}

这可以像这样可视化:

                      child list object
variable              +-----------+
+-------+             |           |
|child  o------------>|           |
+-------+             |           |
                      |           |
                      |           |
                      |           |
                      |           |
                      |           |
                      +-----------+

重用列表的结果将是:

                       child list
                      +-----------+
parent list      +--->|           |
+--------+       |    |-----------|
|        |o----->|    |           |
|--------|       |    |-----------+
|        |o----->|    |           |
|--------|       |    +-----------+
|        |o----->|
|--------|       |
|        |o----->|
|--------|       |
|        |o------+
+--------+

推荐阅读