zoukankan      html  css  js  c++  java
  • C# Hashtable中存入数组、List

    哈希表中存入数组示例代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Collections;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                Hashtable hash1 = new Hashtable();   // 创建哈希表
                Hashtable hash2 = new Hashtable();   // 创建哈希表
    
                string kk = "test";
                int[] data = { 1, 2, 3, 4, 5 }; //数组
                hash1.Add("key", data);  //数组作为值存入哈希表,对应键为key
                hash1.Add(kk, data);
    
                int[] num1 = (int[])hash1["key"]; //取出键为key的值
                int[] num2 = (int[])hash1[kk];    
    
                int x = ((int[])hash1["key"])[2];
                Console.WriteLine("x = " + x);
    
                Console.WriteLine("数组1:");
                foreach (int i in num1)  //打印数组1
                    Console.Write(i + " ");
                Console.WriteLine("
    数组2:");
                foreach (int i in num2)  //打印数组2
                    Console.Write(i + " ");
            }
        }
    }

    输入结果为:

    x = 3
    数组1:
    1 2 3 4 5
    数组2:
    1 2 3 4 5 请按任意键继续. . .

    存入List示例代码:

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleApplication2
    {
        class Program
        {
            static void Main(string[] args)
            {
                List<int> list = new List<int>();
                list.Add(1);
                list.Add(2);
                list.Add(3);
                Console.WriteLine("list :");
                foreach (int a in list)
                    Console.Write(a + "  ");
    
                Hashtable hash = new Hashtable();
                hash.Add("1", list);
    
                Console.WriteLine("
    从哈希表中取出list:");
                List<int> re = (List<int>)hash["1"];
                foreach (int aPart in re)
                    Console.Write(aPart + "  ");
            }
        }
    }

    运行结果:

    list :
    1  2  3
    从哈希表中取出list:
    1  2  3

      代码简单,可以一下就看懂,类的话与之类似。

  • 相关阅读:
    POJ 2486
    奇怪的电梯
    穿越泥地(mud)
    救援行动(save)
    As Fast As Possible
    Connecting Universities
    They Are Everywhere
    Cells Not Under Attack
    吃饭
    花店橱窗(flower)
  • 原文地址:https://www.cnblogs.com/vitah/p/3836217.html
Copyright © 2011-2022 走看看