c#數組與集合


數組在內存中是連續存儲的,所以索引速度很快,增刪改元素也很簡單。但是數組是分配在一塊連續的數據空間上的,因此分配空間的同時就必須確定好空間的大小,空間的連續也導致增刪改及存儲元素的效率很低。如在數組中添加元素,就需在內存空間中“騰出”一塊地方,別的元素再往后“cuan”位置。還有在聲明數組時,必須指定數組長度,長也不好短也不行,怎么辦?於是集合出現了。

ArrayList示例:

static void Main(string[] args)
        {
            ArrayList list = new ArrayList();
            list.Add(true);
            list.Add(1);
            list.Add("張三");
            list.AddRange(new int[] { 1, 2, 3, 4, 5, 6, 7, 8 });
            list.AddRange(list);
            //list.Clear();//清除
            //list.Reverse();//反轉
            //list.InsertRange(0, new string[] {"李四"});//指定位置插入集合
            if (list.Contains("張三"))//判斷包含指定元素
            {
                Console.WriteLine("已經有這個屌絲啦~");
            }
            for (int i = 0; i < list.Count; i++)
            {
                Console.WriteLine(list[i]);
            }
            Console.ReadKey();
        }

List<>示例:

static void Main(string[] args)
        {
            List<int> lt = new List<int>();
            lt.Add(1);
            lt.Add(2);
            lt.Add(3);
            lt.AddRange(new int[] { 4, 5, 6, 7, 8, 9 });
            for (int i = 0; i < lt.Count; i++)
            {
                Console.WriteLine(lt[i]);
            }
            Console.ReadKey();
        }

Hashtable示例:

static void Main(string[] args)
        {
            Hashtable hash = new Hashtable();
            hash.Add(1, "張三");
            hash.Add(2, true);
            hash.Add(false, "錯誤的~");
            foreach (var h in hash.Keys)
            {
                Console.WriteLine("鍵是{0},值是{1}", h, hash[h]);
            }
            Console.ReadKey();
        }

Dictionary示例:

 static void Main(string[] args)
        {
            Dictionary<int, string> dir = new Dictionary<int, string>();
            dir.Add(1, "張三");
            dir.Add(2, "李四");
            dir[1] = "干掉你";
            foreach (KeyValuePair<int, string> kv in dir)
            {
                Console.WriteLine("鍵是{0},值是{1}", kv.Key, kv.Value);
            }
            Console.ReadKey();
        }

小結:

ArrayList集合對數據類型沒有要求,是因為ArrayList集合中存儲的數據類型默為object類型,其它類型與object類型進行轉換時就會發生“拆箱裝箱”操作,而List集合在聲明集合時就確定了數據類型,所以List集合與ArrayList集合相比是相對安全的哦。鍵值對集合與字典集合同理。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM