foreach是取只读的,在取的时候数据队列不能变(包括修改,删除,添加等)。要避免这个问题,就应该使用for循环。

             IList<Person> iList = new List<Person>();

            iList.Add( new Person("david",13));
            iList.Add(new Person("bob", 11));
            iList.Add(new Person("justin",12));
 

// 用linq重新排序 

            var textList = (from c in iList
                orderby c.age
                    select c);

 

            int iPerson =0;
            foreach (Person p in textList)
            {
                // 这时候在immediate Window里面输入iList.RemoveAt(2),程序会抛出异常
                Console.WriteLine(p.name + ":" + p.age);
                iList[iPerson] = p; // 排序后修改原来的队列!!!
                iPerson++;
            }
            for (int ii = 0; ii < iList.Count; ii++)
            {
                // 这时候在immediate Window里面输入iList.RemoveAt(2),程序不会抛出异常
                Console.WriteLine(iList[ii].name);
            }

相关文章:

  • 2021-07-11
  • 2022-12-23
  • 2022-01-18
  • 2022-12-23
  • 2022-12-23
  • 2022-01-09
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-09-06
  • 2022-12-23
  • 2021-11-02
  • 2021-06-15
  • 2021-09-14
  • 2021-11-02
相关资源
相似解决方案