注册
登录

在C#中,集合是用于存储和操作一组数据项的数据结构。这些集合通常位于 System.Collections 和 System.Collections.Generic 命名空间中。下面我将概述C#中几种常用的集合类型及其特点:
System.Collections 命名空间中的集合这个命名空间中的集合类型不支持泛型,因此在编译时不检查类型安全性。这意味着在运行时可能会遇到类型转换错误。
ArrayList
Add, Insert, Remove, Sort, Reverse 等方法。ArrayList list = new ArrayList();
list.Add(1);
list.Add("two");
Hashtable
object 类型。Add, Remove, ContainsKey, ContainsValue 等方法。Hashtable table = new Hashtable();
table.Add("key", "value");
Stack
Push 和 Pop 方法。Stack<object> stack = new Stack<object>();
stack.Push(1);
stack.Push("two");
object top = stack.Pop(); // "two"
Queue
Enqueue 和 Dequeue 方法。Queue<object> queue = new Queue<object>();
queue.Enqueue(1);
queue.Enqueue("two");
object front = queue.Dequeue(); // 1
System.Collections.Generic 命名空间中的集合这个命名空间中的集合类型支持泛型,因此可以确保类型安全性。
List
Add, Insert, Remove, Sort, Reverse 等方法。List<int> numbers = new List<int>();
numbers.Add(1);
numbers.Add(2);
HashSet
Add, Remove, Contains 等方法。var hashSet = new HashSet<string>();
hashSet.Add("a");
hashSet.Add("c");
hashSet.Add("b");
hashSet.Add("a");
hashSet.Add("c");
hashSet.Add("b");
foreach (var item in hashSet)
{
Console.WriteLine(item);
}
/*输出结果
a
b
c
*/
Dictionary<TKey, TValue>
Add, Remove, TryGetValue, ContainsKey 等方法。Dictionary<string, int> scores = new Dictionary<string, int>();
scores.Add("Alice", 90);
scores.Add("Bob", 80);
SortedDictionary<TKey, TValue>
Add, Remove, TryGetValue, ContainsKey 等方法。var sortDic = new SortedDictionary<int, string>();
sortDic.Add(10, "十");
sortDic.Add(5, "五");
sortDic.Add(1, "一");
Console.WriteLine(sortDic.Keys);
foreach (var item in sortDic)
{
Console.WriteLine($"{item.Key}~{item.Value}");
}
/*输出结果
1~一
5~五
10~十
*/
Queue
Enqueue 和 Dequeue 方法。var queue = new Queue<int>();
queue.Enqueue(1);
queue.Enqueue(2);
queue.Enqueue(3);
foreach (var item in queue)
{
Console.WriteLine(item);
}
Console.WriteLine($"dequeue元素:{queue.Dequeue()}");
/*输出结果
1
2
3
dequeue元素:1
*/
Stack
Push 和 Pop 方法。var stack = new Stack<int>();
stack.Push(1);
stack.Push(2);
stack.Push(3);
foreach (var item in stack)
{
Console.WriteLine(item);
}
//pop元素
Console.WriteLine($"pop元素:{stack.Pop()}");
/*输出结果
3
2
1
pop元素:3
*/
LinkedList
AddFirst, AddLast, RemoveFirst, RemoveLast 等方法。var linkedList = new LinkedList<string>();
linkedList.AddLast("2");
linkedList.AddLast("3");
linkedList.AddLast("5");
linkedList.AddFirst("1");
linkedList.AddBefore(linkedList.Find("5"), "4");
foreach (var item in linkedList)
{
Console.WriteLine(item);
}
Console.WriteLine($"2前面的值:{linkedList.Find("2").Previous.Value}");
Console.WriteLine($"2后面的值:{linkedList.Find("2").Next.Value}");
/*输出结果
1
2
3
4
5
2前面的值:1
2后面的值:3
*/