C#数组与集合

🧠 一、数组(Array)

1. 定义和初始化数组

csharp 复制代码
// 定义并初始化数组
int[] numbers = new int[5]; // 默认值为 0

// 声明并赋值
string[] names = { "Tom", "Jerry", "Bob" };

// 使用 new 初始化
double[] scores = new double[] { 90.5, 85.3, 92.7 };

2. 访问和修改元素

csharp 复制代码
Console.WriteLine(names[0]); // 输出 Tom
names[1] = "Alice";
Console.WriteLine(names[1]); // 输出 Alice

3. 数组切片(C# 8.0+)

csharp 复制代码
int[] arr = { 1, 2, 3, 4, 5 };
int[] slice = arr[1..4]; // [2, 3, 4]

4. 遍历数组

csharp 复制代码
foreach (string name in names)
{
    Console.WriteLine(name);
}

5. 数组尺寸(Length)和 Rank

csharp 复制代码
Console.WriteLine($"长度: {names.Length}");
Console.WriteLine($"维度数: {names.Rank}"); // 通常为 1

6. 多维数组(矩形数组)

二维数组:
csharp 复制代码
int[,] matrix = {
    {1, 2},
    {3, 4}
};

Console.WriteLine(matrix[0, 1]); // 输出 2
三维数组:
csharp 复制代码
int[,,] cube = new int[2, 2, 2];
cube[0, 0, 0] = 1;

7. 锯齿数组(Jagged Array)------数组的数组

csharp 复制代码
int[][] jagged = new int[][]
{
    new int[] { 1, 2 },
    new int[] { 3 },
    new int[] { 4, 5, 6 }
};

Console.WriteLine(jagged[2][1]); // 输出 5

8. 常用数组方法(System.Array)

csharp 复制代码
Array.Sort(scores); // 排序
Array.Reverse(scores); // 反转
int index = Array.IndexOf(names, "Alice"); // 查找索引

📦 二、集合(Collections)

1. ArrayList(非泛型)

❗不推荐使用,因为没有类型安全。

csharp 复制代码
ArrayList list = new ArrayList();
list.Add("Apple");
list.Add(100);
list.Remove("Apple");

2. List<T>(泛型集合,推荐使用)

csharp 复制代码
List<string> fruits = new List<string>() { "Apple", "Banana" };
fruits.Add("Orange");
fruits.Remove("Banana");

foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}

3. 集合初始值设定项(Collection Initializers)

csharp 复制代码
List<int> numbersList = new List<int> { 1, 2, 3 };

4. SortedList<TKey, TValue>(按键排序)

csharp 复制代码
SortedList<int, string> sortedList = new SortedList<int, string>
{
    { 3, "Three" },
    { 1, "One" },
    { 2, "Two" }
};

foreach (var item in sortedList)
{
    Console.WriteLine($"{item.Key}: {item.Value}");
}

5. LinkedList<T>(链表结构)

csharp 复制代码
LinkedList<string> linkedList = new LinkedList<string>();
linkedList.AddLast("A");
linkedList.AddLast("B");
linkedList.AddFirst("X");

6. Dictionary<TKey, TValue>(键值对)

csharp 复制代码
Dictionary<string, int> ages = new Dictionary<string, int>
{
    { "Tom", 25 },
    { "Jerry", 30 }
};

ages["Alice"] = 28;

if (ages.ContainsKey("Tom"))
{
    Console.WriteLine(ages["Tom"]);
}

7. Queue<T>(先进先出)

csharp 复制代码
Queue<string> queue = new Queue<string>();
queue.Enqueue("Task 1");
queue.Enqueue("Task 2");

Console.WriteLine(queue.Dequeue()); // Task 1

8. Stack<T>(后进先出)

csharp 复制代码
Stack<int> stack = new Stack<int>();
stack.Push(1);
stack.Push(2);

Console.WriteLine(stack.Pop()); // 2

🧩 三、综合练习项目模板(Program.cs)

csharp 复制代码
using System;
using System.Collections;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Console.WriteLine("=== C# 数组与集合综合练习 ===\n");

        // 1. 数组操作
        int[] nums = { 5, 2, 8, 1 };
        Array.Sort(nums);
        Console.WriteLine("排序后的数组:");
        foreach (int n in nums) Console.Write(n + " ");

        // 2. 多维数组
        int[,] matrix = { { 1, 2 }, { 3, 4 } };
        Console.WriteLine("\n\n矩阵元素:");
        for (int i = 0; i < matrix.GetLength(0); i++)
        {
            for (int j = 0; j < matrix.GetLength(1); j++)
            {
                Console.Write(matrix[i, j] + " ");
            }
            Console.WriteLine();
        }

        // 3. 列表 List<T>
        List<string> fruits = new List<string> { "Apple", "Banana" };
        fruits.Add("Orange");
        Console.WriteLine("\n水果列表:");
        foreach (string f in fruits) Console.WriteLine(f);

        // 4. 字典 Dictionary
        Dictionary<string, int> ages = new Dictionary<string, int>
        {
            { "Tom", 25 },
            { "Jerry", 30 }
        };

        Console.WriteLine("\n年龄信息:");
        foreach (var item in ages)
        {
            Console.WriteLine($"{item.Key}: {item.Value}");
        }

        // 5. 队列 Queue
        Queue<string> queue = new Queue<string>();
        queue.Enqueue("任务1");
        queue.Enqueue("任务2");
        Console.WriteLine("\n队列取出:" + queue.Dequeue());

        // 6. 栈 Stack
        Stack<int> stack = new Stack<int>();
        stack.Push(10);
        stack.Push(20);
        Console.WriteLine("栈取出:" + stack.Pop());

        Console.WriteLine("\n按任意键退出...");
        Console.ReadKey();
    }
}

📋 四、运行效果(模拟)

复制代码
=== C# 数组与集合综合练习 ===

排序后的数组:
1 2 5 8 

矩阵元素:
1 2 
3 4 

水果列表:
Apple
Banana
Orange

年龄信息:
Tom: 25
Jerry: 30

队列取出:任务1
栈取出:20

按任意键退出...

📌 五、总结对比表

类型 是否泛型 是否有序 是否可变 典型用途
Array ❌ ✅ ❌ 固定大小数据存储
List<T> ✅ ✅ ✅ 动态数组
Dictionary<TKey, TValue> ✅ ✅ ✅ 键值查找
SortedList<TKey, TValue> ✅ ✅ ✅ 按键排序
Queue<T> ✅ ✅ ✅ FIFO 场景
Stack<T> ✅ ✅ ✅ LIFO 场景
LinkedList<T> ✅ ✅ ✅ 插入/删除频繁

相关推荐
FRing032 小时前
JavaScript入门到精通三十一(原型继承、原型链)
开发语言·前端·javascript
1024奇点2 小时前
【仓颉语言入门 · 第二篇 第 12 课】
开发语言·数据库·ide·mysql·开源
LDR0062 小时前
LDR6100 智能遥控器精品软文:Type-C 充电口与低功耗量产维护
c语言·开发语言
iCxhust3 小时前
MATLAB SPWM仿真
开发语言·matlab
谙忆3 小时前
PNG改成ICO为什么不能用:用Python检查多尺寸目录与256px帧
开发语言·python
青峰讲运维3 小时前
OpenStack 存储深度解析|Cinder 块存储 + Swift 对象存储原理与完整实操(Yoga)
开发语言·openstack·swift
汤姆宝库3 小时前
具身智能深拆:VLA、世界模型与数据飞轮
开发语言·人工智能·php
云和数据.ChenGuang3 小时前
深入剖析 Python 的 MRO 规则:从 C3 线性化到实战踩坑
开发语言·python·1024程序员节
123_不打狼3 小时前
Squidiff:基于条件扩散模型预测细胞发育与扰动响应
开发语言·python·squidiff
瑞got4 小时前
java使用CountDownLatch做并行查询
java·开发语言