我正在寻找一个更好的模式来处理每个需要处理的元素列表,然后根据结果从列表中删除.
你不能.Remove(element)在里面使用foreach (var element in X)(因为它导致Collection was modified; enumeration operation may not execute.异常)...你也不能使用for (int i = 0; i < elements.Count(); i++),.RemoveAt(i)因为它会扰乱你在集合中的当前位置i.
有一种优雅的方式来做到这一点?
我在foreach循环中从ArrayList中删除项目并获得以下异常.
收集被修改; 枚举操作可能无法执行.
如何删除foreach中的项目,
编辑: 可能有一个项目要删除或两个或全部.
以下是我的代码:
/*
* Need to remove all items from 'attachementsFielPath' which does not exist in names array.
*/
try
{
string attachmentFileNames = txtAttachment.Text.Trim(); // Textbox having file names.
string[] names = attachmentFileNames.Split(new char[] { ';' });
int index = 0;
// attachmentsFilePath is ArrayList holding full path of fiels user selected at any time.
foreach (var fullFilePath in attachmentsFilePath)
{
bool isNeedToRemove = true;
// Extract filename from full path.
string fileName = …Run Code Online (Sandbox Code Playgroud) 你可以在迭代它时从List <>中删除一个项目吗?这会有用,还是有更好的方法呢?
我的代码:
foreach (var bullet in bullets)
{
if (bullet.Offscreen())
{
bullets.Remove(bullet);
}
}
Run Code Online (Sandbox Code Playgroud)
-edit-对不起,伙计们,这是一个银色的游戏.我没有意识到Silverlight与Compact Framework不同.
在c#中,当我想从列表中删除一些项目时,我会按以下方式执行此操作,
List<Item> itemsToBeRemoved = new List<Item>();
foreach(Item item in myList)
{
if (IsMatching(item)) itemsToBeRemoved.Add(item);
}
foreach(Item item in itemsToBeRemoved)
{
myList.Remove(item);
}
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法呢?