[c#] for和foreach

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);
            }
原文地址:https://www.cnblogs.com/linn/p/2513053.html