C# 从列表中删除所有项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9980245/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Delete all items from a list
提问by janneob
I want to delete all the elements from my list:
我想从我的列表中删除所有元素:
foreach (Session session in m_sessions)
{
m_sessions.Remove(session);
}
In the last element I get an exception: UnknownOperation.
在最后一个元素中,我得到一个异常:UnknownOperation。
Anyone know why?
有谁知道为什么?
how should I delete all the elements? It is ok to write something like this:
我应该如何删除所有元素?可以这样写:
m_sessions = new List<Session>();
采纳答案by David Heffernan
You aren't allowed to modify a List<T>whilst iterating over it with foreach. Use m_sessions.Clear()instead.
不允许List<T>在使用foreach. 使用m_sessions.Clear()来代替。
Whilst you could write m_sessions = new List<Session>()this is not a good idea. For a start it is wasteful to create a new list just to clear out an existing one. What's more, if you have other references to the list then they will continue to refer to the old list. Although, as @dasblinkenlight points out, m_sessionsis probably a private member and it's unlikely you have other references to the list. No matter, Clear()is the canonical way to clear a List<T>.
虽然你可以写m_sessions = new List<Session>()这不是一个好主意。首先,创建一个新列表只是为了清除现有列表是一种浪费。更重要的是,如果您对列表有其他引用,那么它们将继续引用旧列表。尽管正如@dasblinkenlight 指出的那样,m_sessions它可能是一个私有成员,并且您不太可能对该列表有其他引用。Clear()无论如何,是清除List<T>.
回答by Kendall Frey
Never, ever, modify a collection that is being iterated on with foreach. Inserting, deleting, and reordering are no-nos. You may, however, modify the foreachvariable (sessionin this case).
永远不要修改正在迭代的集合foreach。插入、删除和重新排序是禁忌。但是,您可以修改foreach变量(session在本例中)。
In this case, use
在这种情况下,使用
m_sessions.Clear();
and eliminate the loop.
并消除循环。
回答by akbar
Try this:
尝试这个:
m_sessions.RemoveRange ( 0 , m_sessions.Count() );

