c# 04集合

c#中的集合功能和java差不多但是用法还是有些区别,例如取值时key要放在[]中,arrayList和List没父子关系,ArrayList和HashTable没有泛型很古老,对应的有泛型的是List和Dictionary(相当于map)。

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApp1 
{
    /// <summary>
    /// 胡萝卜类
    /// </summary>
    class Carrot : Vegetables
    {
        public static void Main(string[] args) {


            ArrayList arrayList = new ArrayList();
            arrayList.Add("混世魔王");
            arrayList.Add(123456);
            foreach (var value in arrayList)
            {
                Console.WriteLine("arrayList---->value:{0}", value);
            }

            Hashtable hashtable = new Hashtable();
            hashtable.Add(1,"aaaa");
            hashtable.Add(true , 1245);
            foreach (var key in hashtable.Keys)
            {
                Console.WriteLine("hashtable---->key:{0},value:{1}", key , hashtable[key]);
            }

            List<int> list = new List<int>();
            list.Add(23);
            list.Add(99);
            Console.WriteLine("list测试 拿出对象索引为1:{0},list的长度:{1}", list[1], list.Count);

            Dictionary<int, string> dictionary = new Dictionary<int, string>();
            dictionary.Add(1,"小明");
            dictionary.Add(2,"小丽");
            Console.WriteLine("单独用可以去取---->key:{0},value:{1}", 2, dictionary[2]);

            foreach (var key in dictionary.Keys)
            {
                Console.WriteLine("var-->key:{0},value{1}",key, dictionary[key]);
            }
            foreach (KeyValuePair<int ,string> kv in dictionary)
            {
                Console.WriteLine("keyValuePair---->key:{0},value:{1}", kv.Key, kv.Value);
            }
        }
    }
}
原文地址:https://www.cnblogs.com/li-yan-long/p/14002023.html