HashTable的Values为ArrayList应该怎么转换?
using System;
public class Class1
{
static void Main()
{
System.Collections.Hashtable ht = new ystem.Collections.Hashtable();
System.Collections.ArrayList al2 = new System.Collections.ArrayList();
while(true)
{
string str = Console.ReadLine();
if(str.Equals("exit"))System.Environment.Exit(1);
string [] s = str.Split(' ');
if(ht.ContainsKey(s[0]))
{
System.Collections.ArrayList al = (System.Collections.ArrayList) ht[s[0]] as System.Collections.ArrayList;
al.Add(s[1]);
ht.Remove(s[0]);
ht.Add(s[0],al);
}
else
{
ht.Add(s[0],al2.Add(s[1]));
}
System.Collections.IDictionaryEnumerator ide = ht.GetEnumerator();
while(ide.MoveNext())
{
System.Collections.ArrayList al = (System.Collections.ArrayList)ide.Value as System.Collections.ArrayList;
Console.WriteLine("ht[key]={0}=======================>",ide.Key);
for(int i=0;i<al.Count;i++)
{
Console.WriteLine("ht[key]={0},ht[value]={1}",ide.Key,al[i]);
}
}
}
}
}
说明:hashtable[key=string][value=ArrayList]
我想打印key下的所有Value元素,而Value放的是ArrayList.
所以Value需要转换一下.我用 as 的方式转换报错!
未处理的异常: System.InvalidCastException: 指定的转换无效。
public class Class1
{
static void Main()
{
System.Collections.Hashtable ht = new ystem.Collections.Hashtable();
System.Collections.ArrayList al2 = new System.Collections.ArrayList();
while(true)
{
string str = Console.ReadLine();
if(str.Equals("exit"))System.Environment.Exit(1);
string [] s = str.Split(' ');
if(ht.ContainsKey(s[0]))
{
System.Collections.ArrayList al = (System.Collections.ArrayList) ht[s[0]] as System.Collections.ArrayList;
al.Add(s[1]);
ht.Remove(s[0]);
ht.Add(s[0],al);
}
else
{
ht.Add(s[0],al2.Add(s[1]));
}
System.Collections.IDictionaryEnumerator ide = ht.GetEnumerator();
while(ide.MoveNext())
{
System.Collections.ArrayList al = (System.Collections.ArrayList)ide.Value as System.Collections.ArrayList;
Console.WriteLine("ht[key]={0}=======================>",ide.Key);
for(int i=0;i<al.Count;i++)
{
Console.WriteLine("ht[key]={0},ht[value]={1}",ide.Key,al[i]);
}
}
}
}
}
说明:hashtable[key=string][value=ArrayList]
我想打印key下的所有Value元素,而Value放的是ArrayList.
所以Value需要转换一下.我用 as 的方式转换报错!
未处理的异常: System.InvalidCastException: 指定的转换无效。
...全文
相关推荐
C#常见的几种集合 ArrayList,Hashtable,List<T>,Dictionary<K,V> 遍历方法对比
本文将对比并介绍四种常见的集合:ArrayList、Hashtable、List<T>以及Dictionary<K,V>的遍历方法。**1.
C#常见的几种集合 ArrayList,Hashtable,ListT,DictionaryK,V 遍历方法对比
"C#常见的几种集合包括ArrayList,Hashtable,List<T>以及Dictionary<K,V>,这些集合各有特点。ArrayList是一个动态数组,适用于存储值类型的数据;Hasht
Hashtable与ArrayList的简单应用
= new ArrayList(hashtable.Values);```##### 3.4 排序对于 `ArrayList`,可以使用 `Sort` 方法对列表进行排序:```csharparrayList.Sort
C#将hashtable值转换到数组中的方法
"C#将hashtable值转换到数组中的方法"在C#编程语言中,哈希表(Hashtable)是一种常用的存储数据结构,它通过键值对的形式存储数据,允许快速查找、添加和删除元素。当需要将哈希表中的
C#泛型专题
,防止类型转换错误。



