【发布时间】:2015-10-24 07:45:33
【问题描述】:
这是错误:
System.InvalidOperationException:集合已修改;枚举操作可能无法执行。
在 System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource 资源)
在 System.Collections.Generic.List1.Enumerator.MoveNextRare()1.Enumerator.MoveNext()
at System.Collections.Generic.List
在 System.Linq.Enumerable.WhereListIterator1.MoveNext()1 来源)
at System.Linq.Enumerable.Count[TSource](IEnumerable
块引用
我使用静态 Dictionary for web api
这是我用于 Web api 的课程:
public class UsersSecureProvider
{
public static ConcurrentDictionary<short, List<UserSecure>> _Users = new ConcurrentDictionary<short, List<UserSecure>>();
public bool Add(short Group, UserSecure Message)
{
try
{
var GetList = GetByKey(Group);
if (GetList != null)
{
GetList.Add(Message);
return Update(Group, GetList, GetList);
}
else
{
GetList = new List<UserSecure>();
GetList.Add(Message);
return Add(Group, GetList);
}
}
catch { }
return false;
}
private bool Add(short key, List<UserSecure> SendUser)
{
return _Users.TryAdd(key, SendUser);
}
public bool Remove(short Key)
{
List<UserSecure> listremove;
return _Users.TryRemove(Key, out listremove);
}
public List<UserSecure> GetByKey(short Group)
{
var listView = new List<UserSecure>();
if (_Users != null)
{
var getList = _Users.TryGetValue(Group, out listView);
}
return listView;
}
public bool Update(short Group, List<UserSecure> oldlist, List<UserSecure> newlist)
{
return _Users.TryUpdate(Group, newlist, oldlist);
}
public void Clear()
{
_Users.Clear();
}
public ConcurrentDictionary<short, List<UserSecure>> GetAll()
{
return _Users;
}
public bool UpdateListByUser(short Group, List<UserSecure> newlist)
{
var OldList = GetByKey(Group);
return _Users.TryUpdate(Group, newlist, OldList);
}
}
我给班级打电话
var _providers = new UsersSecureProvider();
List<UserSecure> GetAll = _providers.GetByKey(1);
if (GetAll != null && GetAll.Any() && GetAll.Where(w => w.UserID == UserID && w.Key == UniqueSecure).Count() > 0)
{
result = true;
}
else
{
_providers.Add(1, new UserSecure { UserID = UserID, Key = UniqueSecure });
}
为什么我会收到这个错误异常?
谢谢。
【问题讨论】:
-
哪一种方法导致了异常?
-
你在哪里调用
Count()函数? -
当您在迭代中添加/删除项目时,通常会发生此错误。这可以通过迭代集合来解决,而不是迭代集合的副本。喜欢:
_Users.ToArray() -
@JeroenvanLangen,问题不在提供 OP 的代码中,而是在某些外部:在某些集合中使用
Count()的地方,我不确定字典的问题 -
@Ori,你在哪里调用函数
Where(...).Count()?
标签: c# asp.net asp.net-mvc list asp.net-web-api