Mde*_*dev -1 c# data-structures
我的两个列表都被修改,我试图避免这种行为......
这里有什么问题?
我有一个'大'列表,我想删除itemsToRemoveList中存在的所有项目,但没有修改原始列表.
我简化了示例代码..
List<string> aList = new List<string>(){"My","name","is", "jeff"}; // cached full list
List<string> bList = aList; // initial copy
List<string> itemsToRemoveList = new List<string>(){"jeff"};
bList.RemoveAll(itemsToRemoveList.Contains); // remove only from copy
foreach (string s in aList)
{
Console.Write(s + " "); // expect "my name is jeff"
}
Console.WriteLine();
foreach (string s in bList)
{
Console.Write(s + " "); // expect "my name is"
}
// however this modifies both collections.
Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)
当你这样做
List<string> bList = aList;
Run Code Online (Sandbox Code Playgroud)
那不是创建新列表.它只是将您的bList变量设置为指向同一列表的引用aList.制作副本的方法是实际创建一个新列表.
List<string> bList = new List<string>(aList);
Run Code Online (Sandbox Code Playgroud)
但如果您还想过滤值,最好使用Linq.
List<string> aList = new List<string>(){"My","name","is", "jeff"};
List<string> itemsToRemoveList = new List<string>(){"jeff"};
List<string> bList = aList.Where(a => !itemsToRemoveList.Contains(a)).ToList();
foreach (string s in aList)
{
Console.Write(s + " ");
}
Console.WriteLine();
foreach (string s in bList)
{
Console.Write(s + " ");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
105 次 |
| 最近记录: |