zoukankan      html  css  js  c++  java
  • C#中Collection和Dictionary的foreach遍历方式

    原文:http://blog.sojingle.net/programming/csharp/csharp-collections-dictionaries-using-foreach

    对于.net Framework中内置的几种集合类,foreach是一种很方便的遍历方式:

    1.非泛型&弱类型的Collections(ArrayList,Queue,Stack):

    使用object:

    ArrayList al = new ArrayList();
    al.Add("hello");
    al.Add(1);
    foreach(object obj in al)
    {
        Console.WriteLine(obj.ToString());
    }

    如果确定ArrayList中的类型的话,也可以用这个类型代理,会自动强转,但若转换不成功,抛出InvalidCastException

    ArrayList al = new ArrayList();
    al.Add("hello");
    al.Add("world");
    foreach(string s in al)
    {
        Console.WriteLine(s);
    }

    2.强类型的Collections(StringCollectionBitArray),可分别使用string和bool而无需强转。

    3.非泛型的Dictionaris(Hashtable, SortedList,StringDictionary等):

    使用DictionaryEntry:

    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遍历,需要两级:

    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>:

    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..)。

  • 相关阅读:
    echarts中label上下两行展示
    vue中去掉地址栏中的#
    vue中登录超时跳转到登录页面设置拦截器
    在table中,tbody没有充满整个table
    vant中dialog的使用
    水位波纹动画兼容ie8
    在vue中使用XLSX导出表格
    elementUI 选择开始结束日期加限制
    element table 合并同类项并输出后台返回数据
    将后台返回的月份201810,201809转换成正常的9月10月
  • 原文地址:https://www.cnblogs.com/linybo/p/13383913.html
Copyright © 2011-2022 走看看