C# 各类集合汇总
在 C# 中有许多不同种类的集合,每种都有其特点和用途,下面对常用的一些集合进行简单的介绍和示例演示。
List
List
下面是一个例子,展示如何在 List
List<string> fruits = new List<string>();
fruits.Add("apple");
fruits.Add("banana");
fruits.Add("grape");
// 遍历 List<string> 中的所有元素并输出
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
// 输出:apple, banana, grape
Dictionary
Dictionary
下面是一个例子,展示如何在 Dictionary
Dictionary<string, int> fruitCount = new Dictionary<string, int>();
fruitCount.Add("apple", 3);
fruitCount.Add("banana", 2);
fruitCount.Add("grape", 5);
// 输出 apple 的数量
Console.WriteLine(fruitCount["apple"]); // 输出:3
// 遍历 Dictionary<string, int> 中的所有键值对并输出
foreach (KeyValuePair<string, int> pair in fruitCount)
{
Console.WriteLine("There are {0} {1}s", pair.Value, pair.Key);
}
// 输出:There are 3 apples
// There are 2 bananas
// There are 5 grapes
Queue
Queue
下面是一个例子,展示如何在 Queue
Queue<string> customers = new Queue<string>();
customers.Enqueue("Alice");
customers.Enqueue("Bob");
customers.Enqueue("Charlie");
// 处理到达顺序
while (customers.Count > 0)
{
Console.WriteLine(customers.Dequeue() + " has been served.");
}
// 输出:Alice has been served.
// Bob has been served.
// Charlie has been served.
Stack
Stack
下面是一个例子,展示如何在 Stack
Stack<string> browsers = new Stack<string>();
browsers.Push("Chrome");
browsers.Push("Firefox");
browsers.Push("Safari");
// 逆处理创建顺序
while (browsers.Count > 0)
{
Console.WriteLine("Chrome has closed " + browsers.Pop() + ".");
}
// 输出:Chrome has closed Safari.
// Chrome has closed Firefox.
// Chrome has closed Chrome.
Conclusion
以上介绍了 C# 中常用的一些集合类型,每种集合都有其特点和用途。在实际编程中,需要根据具体需求选择合适的集合类型来存储数据。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:C#各类集合汇总 - Python技术站