C# 集合类 :(Array、 Arraylist、List、Hashtable、Dictionary、Stack、Queue)

数组 Array

int[] intArray1;

//初始化已声明的一维数组
ArrayList intArray1 = new int[3];
ArrayList intArray1 = new int[3]{
    
    1,2,3};
ArrayList intArray1 = new int[]{
    
    1,2,3};

数组是固定大小的,不能伸缩。
System.Array.Resize 是重新创建新设置大小的数组,废弃以前的数组。

Arraylist

容量会随着需要而适当的扩充

  1. Add()向数组中添加一个元素,
  2. Remove()删除数组中的一个元素
  3. RemoveAt(int i)删除数组中索引值为i的元素
  4. Reverse()反转数组的元素
  5. Sort()以从小到大的顺序排列数组的元素
  6. Clone()复制一个数组
ArrayList al = new ArrayList();

al.Add(100);//单个添加

foreach (int number in new int[6] {
    
     9, 3, 7, 2, 4, 8 })
{
    
    
    al.Add(number);//集体添加方法一//清清月儿
}
int[] number2 = new int[2] {
    
     11, 12 };
al.AddRange(number2);//集体添加方法二
al.Remove(3);//移除值为3的
al.RemoveAt(3);//移除第3个
ArrayList al2 = new ArrayList(al.GetRange(1, 3));//新ArrayList只取旧ArrayList一部份
Console.WriteLine("遍历方法一:");

foreach (int i in al)//不要强制转换
{
    
    
    Console.WriteLine(i);//遍历方法一
}

Console.WriteLine("遍历方法二:");

for (int i = 0; i != al2.Count; i++)//数组是length
{
    
    
    int number = (int)al2[i];//一定要强制转换
    Console.WriteLine(number);//遍历方法二
}

List

可通过索引访问的对象的强类型列表。提供用于对列表进行搜索、排序和操作的方法。
List 类在大多数情况下执行得更好并且是类型安全的

//声明一个List对象,只加入string参数
List<string> names = new List<string>();
names.Add("apple");
names.Add("bobby");
names.Add("carol");

//遍历List
foreach (string name in names)
{
    
    
Console.WriteLine(name);
}

//在List中获取第一个元素
string getAname = name.GetRange(1, 1)[1];

//移除第一个元素
names.RemoveAt(1);	

//向List中插入元素
names.Insert(2, "daddy");

//移除指定元素
names.Remove("carol");

Dictionary

表示键和值的集合。Dictionary遍历输出的顺序,就是加入的顺序,这点与Hashtable不同

Dictionary<string, string> myDic = new Dictionary<string, string>();
myDic.Add("aaa", "111");
myDic.Add("bbb", "222");
myDic.Add("ccc", "333");
myDic.Add("ddd", "444");

//如果添加已经存在的键,add方法会抛出异常。解决add()异常的方法是
//用ContainsKey()方法来判断键是否存在

if (!myDic.ContainsKey("ddd"))
{
    
        
    myDic.Add("ddd", "ddd");
}
else
{
    
    
    Console.WriteLine("此键已经存在:");
}

//而使用索引器来负值时,如果建已经存在,就会修改已有的键的键值,而不会抛出异常
myDic["ddd"]="ddd";
myDic["eee"] = "555";

//使用索引器来取值时,如果键不存在就会引发异常。解决上面的异常的方法是
//使用ContarnsKey() 来判断时候存在键,如果经常要取健值得化最好用 TryGetValue方法来获取集合中的对应键值
string value = "";
if (myDic.TryGetValue("fff", out value))
{
    
    
    Console.WriteLine("""fff""的键值为:" + value );
}
else
{
    
    
    Console.WriteLine("没有找到对应键的键值");
}

//下面用foreach 来遍历键值对
//泛型结构体 用来存储健值对
foreach (KeyValuePair<string, string> kvp in myDic)
{
    
    
    Console.WriteLine("key={0},value={1}", kvp.Key, kvp.Value);
}

//获取值得集合
foreach (string s in myDic.Values)
{
    
    
    Console.WriteLine("value={0}", s);
}

//获取值得另一种方式

Dictionary<string, string>.ValueCollection values = myDic.Values;
foreach (string s in values)
{
    
    
    Console.WriteLine("value={0}", s);
}

SortedList

与Hashtable类似,区别在于SortedList中的Key数组排好序的

System.Collections.SortedList list=new System.Collections.SortedList();

list.Add("key2",2);
list.Add("key1",1);

for(int i=0;i<list.Count;i++)
{
    
    
System.Console.WriteLine(list.GetKey(i));
}

Hashtable

哈希表,名-值对。类似于字典(比数组更强大)。哈希表是经过优化的,以任意类型键值访问其中元素会快于其他集合。

GetHashCode()方法返回一个int型数据,使用这个键的值生成该int型数据。哈希表获取这个值最后返回一个索引,表示带有给定散列的数据项在字典中存储的位置。

Hashtable 和 Dictionary <K, V> 类型
1:单线程程序中推荐使用 Dictionary, 有泛型优势, 且读取速度较快, 容量利用更充分.
2:多线程程序中推荐使用 Hashtable, 默认的 Hashtable 允许单线程写入, 多线程读取, 对 Hashtable 进一步调用Synchronized() 方法可以获得完全线程安全的类型. 而 Dictionary 非线程安全, 必须人为使用 lock 语句进行保护, 效率大减.
3:Dictionary 有按插入顺序排列数据的特性 (注: 但当调用 Remove() 删除过节点后顺序被打乱), 因此在需要体现顺序的情境中使用 Dictionary 能获得一定方便.

HashTable中的key/value均为object类型,由包含集合元素的存储桶组成。存储桶是 HashTable中各元素的虚拟子组,与大多数集合中进行的搜索和检索相比,存储桶可令搜索和检索更为便捷。每一存储桶都与一个哈希代码关联,该哈希代码是使用哈希函数生成的并基于该元素的键。HashTable的优点就在于其索引的方式,速度非常快。如果以任意类型键值访问其中元素会快于其他集合,特别是当数据量特别大的时候,效率差别尤其大。

HashTable的应用场合有:做对象缓存,树递归算法的替代,和各种需提升效率的场合。

//Hashtable sample
System.Collections.Hashtable ht = new System.Collections.Hashtable();
//--Be careful: Keys can't be duplicated, and can't be null----
ht.Add(1, "apple");
ht.Add(2, "banana");
ht.Add(3, "orange");     
//Modify item value:
if(ht.ContainsKey(1))
    ht[1] = "appleBad"; 
//The following code will return null oValue, no exception
object oValue = ht[5];      
//traversal 1:
foreach (DictionaryEntry de in ht)
{
    
    
    Console.WriteLine(de.Key);
    Console.WriteLine(de.Value);
} 
//traversal 2:
System.Collections.IDictionaryEnumerator d = ht.GetEnumerator();
while (d.MoveNext())
{
    
    
    Console.WriteLine("key:{0} value:{1}", d.Entry.Key, d.Entry.Value);
} 
//Clear items
ht.Clear();

Dictionary和HashTable内部实现差不多,但前者无需装箱拆箱操作,效率略高一点。

//Dictionary sample
System.Collections.Generic.Dictionary<int, string> fruits = new System.Collections.Generic.Dictionary<int, string>();
fruits.Add(1, "apple");
fruits.Add(2, "banana");
fruits.Add(3, "orange"); 
foreach (int i in fruits.Keys)
{
    
    
    Console.WriteLine("key:{0} value:{1}", i, fruits);     }

if (fruits.ContainsKey(1))
{
    
    
    Console.WriteLine("contain this key.");
}

HashTable是经过优化的,访问下标的对象先散列过,所以内部是无序散列的,保证了高效率,也就是说,其输出不是按照开始加入的顺序,而Dictionary遍历输出的顺序,就是加入的顺序,这点与Hashtable不同。如果一定要排序HashTable输出,只能自己实现:

//Hashtable sorting
System.Collections.ArrayList akeys = new System.Collections.ArrayList(ht.Keys); //from Hashtable
akeys.Sort(); //Sort by leading letter
foreach (string skey in akeys)
{
    
    
    Console.Write(skey + ":");
    Console.WriteLine(ht[skey]);
}

Stack

栈,后进先出。push方法入栈,pop方法出栈。

System.Collections.Stack stack=new System.Collections.Stack();
stack.Push(1);
stack.Push(2);

System.Console.WriteLine(stack.Peek());
while(stack.Count>0)
{
    
    
System.Console.WriteLine(stack.Pop());
}

Queue

队列,先进先出。enqueue方法入队列,dequeue方法出队列。

System.Collections.Queue queue=new System.Collections.Queue();
queue.Enqueue(1);
queue.Enqueue(2);

System.Console.WriteLine(queue.Peek());
while(queue.Count>0)
{
    
    
System.Console.WriteLine(queue.Dequeue());
}

原文出处

猜你喜欢

转载自blog.csdn.net/MikeW138/article/details/90749260