我想在不知道键值的情况下从modelState中获取所有错误消息.循环以获取ModelState包含的所有错误消息.
我怎样才能做到这一点?
我正在寻找一个更好的模式来处理每个需要处理的元素列表,然后根据结果从列表中删除.
你不能.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.
有一种优雅的方式来做到这一点?
可能重复:
收集已修改; 枚举操作可能无法执行
嗨,您好,
我正在创建一个项目估算程序,并收到以下错误:C#Collection已被修改; 枚举操作可能无法执行.
它与使用它有关:我最初在全球范围内声明了这个:
Dictionary<int, int> rankings = new Dictionary<int, int>();
Run Code Online (Sandbox Code Playgroud)
包含此字典的Next方法执行以下操作:
private void getFirstEstimation()
{
List<int> array = new List<int>();
string strConnection = ConfigurationSettings.AppSettings["ConnectionString"];
MySqlConnection connection = new MySqlConnection(strConnection);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader reader;
command.CommandText = "SELECT idprojects FROM `test`.`projects` WHERE application_layers = " + applicationTiers;
connection.Open();
reader = command.ExecuteReader();
while (reader.Read())
{
array.Add(Convert.ToInt32(reader["idprojects"].ToString()));
}
foreach (int i in array)
{
rankings[i] = 15;
}
connection.Close();
}
Run Code Online (Sandbox Code Playgroud)
我在这里第二次叫它:
private void getSecondEstimation()
{
Dictionary<int, string> sqltext …Run Code Online (Sandbox Code Playgroud) 我试图使用OpenXML从.docx文件中删除段落(我使用一些占位符文本从docx模板文件生成),但每当我删除段落时,它会破坏我用来迭代的foreach循环.
MainDocumentPart mainpart = doc.MainDocumentPart;
IEnumerable<OpenXmlElement> elems = mainPart.Document.Body.Descendants();
foreach(OpenXmlElement elem in elems){
if(elem is Text && elem.InnerText == "##MY_PLACE_HOLDER##")
{
Run run = (Run)elem.Parent;
Paragraph p = (Paragraph)run.Parent;
p.RemoveAllChildren();
p.Remove();
}
}
Run Code Online (Sandbox Code Playgroud)
这工作,删除我的占位符和它所在的段落,但foreach循环停止迭代.在foreach循环中我需要做更多的事情.
这是正常使用的OpenXML和删除在C#中的段落方式为什么我的foreach循环停止或如何使它不会停止?谢谢.
我有多线程应用程序,我得到这个错误
************** Exception Text **************
System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
at System.Collections.Generic.List`1.Enumerator.MoveNext()
...
Run Code Online (Sandbox Code Playgroud)
我的收藏可能有问题,因为在一个线程上我读取了我的收藏,在另一个线程上我修改了收藏.
public readonly ObservableCollectionThreadSafe<GMapMarker> Markers = new ObservableCollectionThreadSafe<GMapMarker>();
public void problem()
{
foreach (GMapMarker m in Markers)
{
...
}
}
Run Code Online (Sandbox Code Playgroud)
我试图用这段代码锁定集合,但不起作用.
public void problem()
{
lock(Markers)
{
foreach (GMapMarker m in Markers)
{
...
}
}
}
Run Code Online (Sandbox Code Playgroud)
有什么想法来解决这个问题?
这是一个只有我正在编写和使用的小程序.
现在我要编写所有使用导致此问题的hashset的区域的代码
我不明白这是怎么可能的.此项目仅在MainWindow中使用
hsProxyList是一个哈希集
HashSet<string> hsProxyList = new HashSet<string>();
Run Code Online (Sandbox Code Playgroud)
错误发生在下面的迭代中
lock (hsProxyList)
{
int irRandomProxyNumber = GenerateRandomValue.GenerateRandomValueMin(hsProxyList.Count, 0);
int irLocalCounter = 0;
foreach (var vrProxy in hsProxyList)
{
if (irLocalCounter == irRandomProxyNumber)
{
srSelectedProxy = vrProxy;
break;
}
irLocalCounter++;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我使用hsProxyList的其他地方
我在计算时没有锁定对象 - 我想这不会导致任何错误但可能不正确 - 不重要
lblProxyCount.Content = "remaining proxy count: " + hsProxyList.Count;
Run Code Online (Sandbox Code Playgroud)
新
lock (hsProxyList)
{
hsProxyList.Remove(srSelectedProxy);
}
Run Code Online (Sandbox Code Playgroud)
新
lock (hsProxyList)
{
hsProxyList = new HashSet<string>();
foreach (var vrLine in File.ReadLines(cmbBoxSelectProxy.SelectedItem.ToString()))
{
hsProxyList.Add(vrLine);
}
}
Run Code Online (Sandbox Code Playgroud)
可以看出我到处都在使用锁.这是一个多线程软件.所有hsProxyList都在MainWindow.xaml.cs中使用 …
当我尝试使用具有多个表的iTextSharp构建PDF文件时,我收到以下错误消息:
无法访问封闭的Stream.
这是我的代码:
//Create a byte array that will eventually hold our final PDF
Byte[] bytes;
List<TableObject> myTables = getTables();
TableObject currentTable = new TableObject();
//Boilerplate iTextSharp setup here
//Create a stream that we can write to, in this case a MemoryStream
using (MemoryStream ms = new MemoryStream())
{
//Create an iTextSharp Document which is an abstraction of a PDF but **NOT** a PDF
using (Document doc = new Document(PageSize.A4, 10f, 10f, 10f, 0f))
{
foreach (TableObject to in myTables) …Run Code Online (Sandbox Code Playgroud) 我有一个ObservableCollection日志,我通过属性绑定到我的GUI
public ObservableCollection<ILog> Logs {get; private set;}
Run Code Online (Sandbox Code Playgroud)
需要在其他地方显示日志的子集,所以我有:
public ObservableCollection<ILog> LogsForDisplay
{
get
{
ObservableCollection<ILog> displayLogs = new ObservableCollection<ILog>();
foreach (Log log in Logs.ToList()) // notice the ToList()
{
if (log.Date != DateTime.Now.Day)
continue;
displayLogs.Add(log);
}
return displayLogs;
}
Run Code Online (Sandbox Code Playgroud)
在我添加"ToList()"之前,我偶尔会遇到"收集被修改;枚举操作可能无法执行"的例外情况.有意义的是 - 当我迭代它时,有人可以添加到Logs.我从Collection中修改了"ToList"的想法; 枚举操作可能不会执行,这似乎表明ToList是要走的路,并暗示它的线程安全.但是ToList()线程安全吗?我假设在内部它必须使用列表并迭代它?如果有人同时添加该列表怎么办?仅仅因为我没有看到问题并不意味着没有问题.
我的问题.ToList()线程是否安全?如果没有,保护日志的最佳模式是什么?如果ToList()是线程安全的,你有引用吗?
奖金问题.如果要求改变,我需要在GUI上显示的是LogsForDisplay和NOT Logs,我可以将Logs更改为其他可以解决问题的东西吗?如ImmutableList?然后,我不必调用ToList <>,我认为这需要一些时间来制作副本.
如果我能提供澄清,请告诉我.谢谢,
戴夫
string field = ViewState["Field"].ToString();
DataTable dt = (DataTable)Session["Academic"];
foreach (DataRow dr in dt.Rows)
{
if (dr["Degree"].ToString() == field)
{
dr.Delete();
dt.AcceptChanges();
}
}
Session["Academic"] = dt;
gdvwAcademic1.DataSource = Session["Academic"] as DataTable;
gdvwAcademic1.DataBind();
Run Code Online (Sandbox Code Playgroud)
执行此代码时会引发错误,因为“集合已修改,枚举操作可能无法执行”。为什么这样..?
我正在尝试实现一种用于安全地枚举集合的缓存机制,并且正在检查内置集合的所有修改是否触发了InvalidOperationException由其各自的枚举器抛出的异常。我注意到,在.NET Core平台中,Dictionary.Remove和Dictionary.Clear方法没有触发此异常。这是错误还是功能?
范例Remove:
var dictionary = new Dictionary<int, string>();
dictionary.Add(1, "Hello");
dictionary.Add(2, "World");
foreach (var entry in dictionary)
{
var removed = dictionary.Remove(entry.Key);
Console.WriteLine($"{entry} removed: {removed}");
}
Console.WriteLine($"Count: {dictionary.Count}");
Run Code Online (Sandbox Code Playgroud)
输出:
[1,Hello]已删除:True
[2,World]已删除:True
计数:0
范例Clear:
var dictionary = new Dictionary<int, string>();
dictionary.Add(1, "Hello");
dictionary.Add(2, "World");
foreach (var entry in dictionary)
{
Console.WriteLine(entry);
dictionary.Clear();
}
Console.WriteLine($"Count: {dictionary.Count}");
Run Code Online (Sandbox Code Playgroud)
输出:
[1,您好]
计数:0
预期的例外是:
InvalidOperationException:集合已被修改;枚举操作可能无法执行。
...由方法Add以及.NET Framework中的相同方法抛出。
.NET Core 3.0.0,C#8,VS 2019 …
c# ×8
asp.net ×2
collections ×2
dictionary ×2
.net ×1
.net-core ×1
asp.net-mvc ×1
enumerator ×1
generics ×1
itextsharp ×1
key-value ×1
list ×1
locking ×1
loops ×1
modelstate ×1
openxml ×1
tolist ×1