C#中Collection和Dictionary的foreach遍历方式
原文:http://blog.sojingle.net/programming/csharp/csharp-collections-dictionaries-using-foreach
对于.net Framework中内置的几种集合类,foreach是一种很方便的遍历方式:
1.非泛型&弱类型的Collections(ArrayList,Queue,Stack):
使用object:
1 2 3 4 5 6 7 | ArrayList al = new ArrayList(); al.Add( "hello" ); al.Add(1); foreach ( object obj in al) { Console.WriteLine(obj.ToString()); } |
如果确定ArrayList中的类型的话,也可以用这个类型代理,会自动强转,但若转换不成功,抛出InvalidCastException。
1 2 3 4 5 6 7 | ArrayList al = new ArrayList(); al.Add( "hello" ); al.Add( "world" ); foreach ( string s in al) { Console.WriteLine(s); } |
2.强类型的Collections(StringCollection和BitArray),可分别使用string和bool而无需强转。
3.非泛型的Dictionaris(Hashtable, SortedList,StringDictionary等):
使用DictionaryEntry:
1 2 3 4 5 6 7 | Hashtable ht = new Hashtable(); ht.Add(1, "Hello" ); ht.Add(2, "World" ); foreach (DictionaryEntry de in ht) { Console.WriteLine(de.Value); } |
特殊的Dictionary(NameValueCollection):
不能直接对NameValueCollection进行foreach遍历,需要两级:
1 2 3 4 5 6 7 8 9 10 11 | NameValueCollection nvc = new NameValueCollection(); nvc.Add( "a" , "Hello" ); nvc.Add( "a" , "World" ); nvc.Add( "b" , "!" ); foreach ( string key in nvc.AllKeys) { foreach ( string value in nvc.GetValues(key)) { Console.WriteLine(value); } } |
4.泛型Collections
List<T>,Queue<T>,Stack<T>: 这个好说,foreach T 就可以了。
5.Dictionary<Tkey,TValue>和SortedList<Tkey,TValue> 要使用KeyValuePair<Tkey,TValue>:
1 2 3 4 5 6 7 | Dictionary< int , string > dic = new Dictionary< int , string >(); dic.Add(1, "Hello" ); dic.Add(2, "World" ); foreach (KeyValuePair< int , string > pair in dic) { Console.WriteLine(pair.Value); } |
注意 : 在foreach过程中,集合类长度的改变会导致错误,因此foreach的循环体中不要有对集合类的增减操作。而Dictionary<Tkey,TValue>是非线程安全的,多线程时对其使用foreach可能会引起错误,多线程时推荐使用非泛型的Hashtable(或者自己lock..)。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App