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("\n数组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("\n从哈希表中取出list:");
            List<int> re = (List<int>)hash["1"];
            foreach (int aPart in re)
                Console.Write(aPart + "  ");
        }
    }
}

运行结果:

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

 

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

转载于:https://www.cnblogs.com/vitah/p/3836217.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值