private void findManagerForSelectedDate(String dateSelected)
{
dateSelected = dateTimePicker1.Value.ToShortDateString();
List<String> managerNames = new List<String>();
foreach(var item in managers)
{
foreach (var subitem in item)
{
CalendarModel c = subitem;
Console.WriteLine(c.date);
c.name = new CultureInfo("en-US", false).TextInfo.ToTitleCase(c.name);
if (userSelection.Count > 0)
{
foreach (var addedUser in userSelection)
// Crashing here with An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll
{
if (!addedUser.Contains(c.name))
{
userSelection.Add(c.name);
}
}
} else
{
userSelection.Add(c.name);
}
它能够通过我的列表迭代3次,然后在第4次,它崩溃了。
“例外”详细信息说 {“集合已修改;枚举操作可能无法执行。”}
答案 0 :(得分:1)
您可以将用户添加到临时列表中,并将此临时列表添加到最后的原始列表中:
private void findManagerForSelectedDate(String dateSelected)
{
dateSelected = dateTimePicker1.Value.ToShortDateString();
List<string> tempUsersToAdd = new List<string>();
List<String> managerNames = new List<String>();
foreach(var item in managers)
{
foreach (var subitem in item)
{
CalendarModel c = subitem;
Console.WriteLine(c.date);
c.name = new CultureInfo("en-US", false).TextInfo.ToTitleCase(c.name);
if (userSelection.Count > 0)
{
foreach (var addedUser in userSelection)
{
if (!addedUser.Contains(c.name))
{
tempUsersToAdd.Add(c.name);
}
}
}
else
{
tempUsersToAdd.Add(c.name);
}
}
}
userSelection.AddRange(tempUsersToAdd);
答案 1 :(得分:0)
使用foreach循环迭代它时,您无法编辑集合
黑客将迭代你的收藏品副本:
<div class="form-group">
<label for="time">Time of Event</label>
<input id="time" class="timepicker" >
</input>
</div>
<script>
$(document).ready(function() {
$('input.timepicker').timepicker({});
});
</script>
并保持相同的代码
答案 2 :(得分:-1)
您可以使用linq来测试c.name
是否在userSelection
if(!userSelection.Exists( u => u.Contains(c.name))) userSelection.Add(c.name);
当然你需要using System.Linq