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};

The array is of fixed size and cannot be scaled.
System.Array.Resize is to recreate the newly set size array and discard the previous array.

Arraylist

Capacity will be appropriately expanded as needed

  1. Add() adds an element to the array,
  2. Remove() delete an element in the array
  3. RemoveAt(int i) delete the element with index i in the array
  4. Reverse() reverse the elements of an array
  5. Sort() arranges the elements of the array in ascending order
  6. Clone() copies an array
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

A strongly typed list of objects accessible through the index. Provides methods for searching, sorting, and manipulating lists.
The List class performs better in most cases and is type safe

//声明一个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

Represents a collection of keys and values. The order of Dictionary traversal output is the order of adding, which is different from 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

Similar to Hashtable, the difference is that the Key array in SortedList is sorted

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

Hash table, name-value pairs. Similar to a dictionary (more powerful than an array). The hash table is optimized, and accessing its elements with any type of key value will be faster than other collections.

The GetHashCode() method returns an int type data, and the int type data is generated using the value of this key. The hash table obtains this value and finally returns an index indicating the location in the dictionary where the data item with the given hash is stored.

Hashtable and Dictionary <K, V> Type
1: Dictionary is recommended for single-threaded programs, which has the advantages of generics, faster reading speed, and full capacity utilization.
2: Hashtable is recommended for multi-threaded programs, and the default Hashtable allows Single-threaded writing, multi-threaded reading, and further calls to the Synchronized() method on Hashtable can obtain a completely thread-safe type. Dictionary is not thread-safe and must be protected by artificial lock statements, which greatly reduces efficiency.
3: Dictionary has press inserts The feature of orderly arranging data (note: but the order is disrupted when the node is deleted by calling Remove()), so it is convenient to use Dictionary in situations that need to reflect the order.

The key/value in the HashTable are all object types, which consist of storage buckets containing collection elements. Buckets are virtual subgroups of elements in HashTable. Compared with searches and retrievals performed in most collections, buckets can make searching and retrieval more convenient. Each bucket is associated with a hash code, which is generated using a hash function and based on the key of the element. The advantage of HashTable lies in its indexing method, which is very fast. If you access the elements with any type of key value, it will be faster than other collections, especially when the amount of data is particularly large, the efficiency difference is particularly large.

HashTable applications include: object caching, tree recursive algorithm replacement, and various occasions where efficiency needs to be improved.

//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();

The internal implementation of Dictionary and HashTable is similar, but the former does not require boxing and unboxing operations, which is slightly more efficient.

//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 is optimized. The objects that access the subscripts are hashed first, so the internal hashing is disorderly, ensuring high efficiency, that is, its output is not in the order in which it is added, but the order in which the Dictionary traverses the output is The order of joining is different from Hashtable. If you must sort the output of HashTable, you can only implement it yourself:

//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

Stack, last in, first out. Push method pushes the stack, pop method pops the stack.

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

Queue, first in first out. The enqueue method enters the queue, and the dequeue method leaves the queue.

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());
}

Original source

Guess you like

Origin blog.csdn.net/MikeW138/article/details/90749260
Recommended