惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Recent Announcements
Recent Announcements
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
MongoDB | Blog
MongoDB | Blog
H
Help Net Security
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
人人都是产品经理
人人都是产品经理
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
The GitHub Blog
The GitHub Blog
V
V2EX
Microsoft Security Blog
Microsoft Security Blog
V
Visual Studio Blog
A
About on SuperTechFans
博客园_首页
L
LangChain Blog
量子位
雷峰网
雷峰网
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Jina AI
Jina AI
月光博客
月光博客
阮一峰的网络日志
阮一峰的网络日志
博客园 - 聂微东
Microsoft Azure Blog
Microsoft Azure Blog
M
MIT News - Artificial intelligence
N
Netflix TechBlog - Medium

博客园 - xqiwei

WCF RIA Services DomainService life-cycle and adding Transactions C#多线程 使用委托更新UI实例(WP7开发 其他线程中更新UI)(转载) Delegate,Action,Func,匿名方法,匿名委托,事件 (转载) LineBreak in a tooltip in xaml - xqiwei GetObjectbyKey in E.F. vs. Querying for a single entity Use GetObjectByKey() for better performance Visual Studio集成开发环境无法启动调试 C#中关于String.Equals(object,object)和(object==object )的比较 - xqiwei - 博客园 IValueConverter 接口 ASP.NET页面生命周期和asp.net应用程序生命周期 Windows Presentation Foundation Tools and Controls ArcEngine开发之Command控件使用篇 Resharper进阶 C# 中的委托和事件 WPF系列文章 新技术文章 flash与javascript、asp.net(数据库)的交互 使用vs.net ajax实现幻灯片的效果 职业规划
looping(and modifying) a collection - xqiwei
xqiwei · 2010-09-06 · via 博客园 - xqiwei

Ok, back to basics with this one.

I have a collection of strings:

1 List<string> someStrings = new List<string>() { "aaaaaaa", "bbb", "ccc", "dddddddd" };

And I want to remove the shorter items (with length < 4), so there should remain two items left.

My first (and amateuristic) attempt was this:

1 foreach (string s in someStrings)
4       someStrings.Remove(s);

I always use the foreach loop, but it can’t be used when modifying the collection. (You CAN modify properties of the items in the loop, but not the item reference itself!).
When you do try, you’ll get the “InvalidOperationException: Collection was modified; enumeration operation may not execute.

Somewhere in my gray mass, I reminded to use the for-loop. My second (and dangerous) attempt was this:

1 for (int i = 0; i < someStrings.Count; i++)
3    if (someStrings[i].Length < 4)
4       someStrings.RemoveAt(i);

No exceptions were thrown, but the outcome is not what you’d expect!! Due to the fact that someStrings.Count and i are out of sync, the item “ccc” is skipped.

So, here’s the correct code:

1 for (int i = someStrings.Count - 1; i >= 0; i--)
3     if(someStrings[i].Length < 4)
4         someStrings.RemoveAt(i);

Conclusion: use the for-loop and iterate backwards! :p