mscorlib.dll中发生了未处理的“System.InvalidOperationException”类型异常

时间:2017-02-21 15:32:22

标签: c# list dictionary

    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次,它崩溃了。

“例外”详细信息说 {“集合已修改;枚举操作可能无法执行。”}

3 个答案:

答案 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