[英]How to remove list of items while iterating and re-iterate with modified list in C#
I have a list of strings say List1
and for each item
of List1
, another list will be generated dynamically inside foreach
loop.我有一个字符串列表,比如
List1
,对于List1
的每个item
,将在foreach
循环内动态生成另一个列表。 If generated list items are existed in List1
for any item
, those items should be removed from List1
and re-iterated with rest of List1
items如果生成的列表项存在于
List1
中的任何item
,则应从List1
中删除这些项,并使用List1
项的 rest 重新迭代
Example: Lets say for item1
, List2
is generated示例:假设为
item1
,生成List2
ForEach loop started: ForEach 循环开始:
1st loop第一个循环
-- item1 --> Generated List say List2
-- item1 --> remove the List2 items from List1 ( In this case, items(item1,item2,item4) are removed and re-iterate List1 with only 'item3'
2nd loop第二循环
-- item3 ---> generated List say List3
-- item3 ---> check and remove the List3 items from List1 if existed
Loop Ends.循环结束。
What is best way to achieve this?实现这一目标的最佳方法是什么?
private static void IterateListAndRemoveItemsWhileIterating()
{
List<string> list1 = new List<string>();
list1.Add("item1");
list1.Add("item2");
list1.Add("item3");
list1.Add("item4");
List<string> list2 = new List<string>();
list2.Add("item1");
list2.Add("item2");
list2.Add("item4");
foreach (var item in list1.ToList())
{
Console.WriteLine(item);
//Do some logic with each item and get another list of Items and then remove from List1. (Ex: List2 which is another list of items after processing some logic with item1)
list1.RemoveAll(r => list2.Contains(r)); // After removing list2 items in list1, I want to re-iterate with rest of items but its not happening
}
}
Actual Output:实际 Output:
item1
item3
item2
item4
Expected Output:预期 Output:
item1
item3
Your variable names are ambiguous item is the name of the variable from the foreach loop and the lambda syntax.您的变量名称不明确项目是来自 foreach 循环和 lambda 语法的变量名称。 so the compiler may be using the foreach variable in your lambda meaning you would get all the items in list1 printed to console.
因此编译器可能在您的 lambda 中使用 foreach 变量,这意味着您会将 list1 中的所有项目打印到控制台。 try changing one of the var names like this:
尝试像这样更改其中一个 var 名称:
foreach (var item in list1.ToList())
{
Console.WriteLine(item);
list1.RemoveAll(s => list2.Contains(s));
}
I hope that will get you the intended result我希望这会给你带来预期的结果
Correction更正
using list1.ToList()
makes a clone of the original list so the enumerable wont change on the foreach loop even if you make changes to the original list.使用
list1.ToList()
会克隆原始列表,因此即使您对原始列表进行了更改,枚举也不会在 foreach 循环中发生变化。 you can avoid this by keeping a second list:您可以通过保留第二个列表来避免这种情况:
List<string> enumerationList = list1.ToList();
foreach (var item in enumerationList)
{
if(list1.Contains(item))
{
Console.WriteLine(item);
list1.RemoveAll(s => list2.Contains(s));
}
}
I am sure there are other ways to do this as well.我相信还有其他方法可以做到这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.