c# - 如何在 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>();
在循环内使用,但这不是我的选择。
解决方案
您不能重复使用子列表。列表是类,因此是引用类型。这意味着您实际上并没有将子列表对象本身存储在父列表中,而是引用您创建的唯一子列表。结果,列表的所有位置都指向同一个唯一的子列表。您必须每次都创建一个新的子列表。
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------+
+--------+
推荐阅读
- node.js - 订阅过期后无法获取key的值
- powershell - powershell - 远程磁盘信息唯一描述
- c++ - C++中的BLE扫描和通信
- html - 什么 VSCODE 扩展将短标签和类语句转换为扩展代码(内部示例)
- api - Tradingview 的 REST API 和盈透证券都通过 python 连接成功?
- javascript - Firebase onIdTokenChanged 函数文档
- json - API 测试:无法建立连接,因为目标机器主动拒绝它
- c++ - Win32窗口类注册线程安全吗?
- laravel-nova - 如何在 HasMany 字段 Laravel Nova 中获取父 ID
- json - Dynamics NAV Odata 请求返回 HTTP/1.1 415 Unsupported Media Type