Skip to content

C# 数组和集合

本章将详细介绍 C# 中的数组和集合类型,包括一维数组、多维数组、交错数组以及常用的集合类,帮助你有效地存储和操作多个数据项。

数组基础

一维数组

数组声明和初始化

csharp
// 声明数组
int[] numbers;                    // 声明但未初始化
string[] names = new string[5];   // 声明并分配空间

// 初始化数组
int[] scores = new int[3];        // 创建包含3个元素的数组,默认值为0
scores[0] = 85;
scores[1] = 92;
scores[2] = 78;

// 声明并初始化
int[] grades = new int[] { 85, 92, 78, 96, 88 };
string[] cities = { "北京", "上海", "广州", "深圳" };  // 简化语法

// 使用 var 关键字
var temperatures = new double[] { 25.5, 28.3, 22.1, 30.0 };

数组访问和操作

csharp
int[] numbers = { 10, 20, 30, 40, 50 };

// 访问数组元素
Console.WriteLine($"第一个元素: {numbers[0]}");      // 10
Console.WriteLine($"最后一个元素: {numbers[4]}");     // 50

// 修改数组元素
numbers[2] = 35;
Console.WriteLine($"修改后的第三个元素: {numbers[2]}"); // 35

// 数组长度
Console.WriteLine($"数组长度: {numbers.Length}");

// 遍历数组
Console.WriteLine("使用 for 循环:");
for (int i = 0; i < numbers.Length; i++)
{
    Console.WriteLine($"numbers[{i}] = {numbers[i]}");
}

Console.WriteLine("使用 foreach 循环:");
foreach (int number in numbers)
{
    Console.WriteLine($"数字: {number}");
}

多维数组

二维数组

csharp
// 声明和初始化二维数组
int[,] matrix = new int[3, 4];  // 3行4列的二维数组

// 初始化时赋值
int[,] grid = {
    { 1, 2, 3, 4 },
    { 5, 6, 7, 8 },
    { 9, 10, 11, 12 }
};

// 访问二维数组元素
Console.WriteLine($"第2行第3列的元素: {grid[1, 2]}");  // 7

// 获取维度信息
Console.WriteLine($"行数: {grid.GetLength(0)}");      // 3
Console.WriteLine($"列数: {grid.GetLength(1)}");      // 4
Console.WriteLine($"总元素数: {grid.Length}");        // 12

// 遍历二维数组
Console.WriteLine("二维数组内容:");
for (int row = 0; row < grid.GetLength(0); row++)
{
    for (int col = 0; col < grid.GetLength(1); col++)
    {
        Console.Write($"{grid[row, col]}\t");
    }
    Console.WriteLine();
}

三维数组

csharp
// 三维数组:立方体数据结构
int[,,] cube = new int[2, 3, 4];  // 2层,每层3行4列

// 初始化三维数组
for (int layer = 0; layer < cube.GetLength(0); layer++)
{
    for (int row = 0; row < cube.GetLength(1); row++)
    {
        for (int col = 0; col < cube.GetLength(2); col++)
        {
            cube[layer, row, col] = layer * 100 + row * 10 + col;
        }
    }
}

// 访问三维数组
Console.WriteLine($"cube[1,2,3] = {cube[1, 2, 3]}");  // 123

交错数组(锯齿数组)

csharp
// 交错数组:数组的数组,每个子数组可以有不同的长度
int[][] jaggedArray = new int[3][];

// 初始化每个子数组
jaggedArray[0] = new int[] { 1, 2, 3 };
jaggedArray[1] = new int[] { 4, 5, 6, 7, 8 };
jaggedArray[2] = new int[] { 9, 10 };

// 声明并初始化交错数组
int[][] scores = {
    new int[] { 85, 92, 78 },
    new int[] { 88, 95, 82, 90 },
    new int[] { 91, 87 }
};

// 访问交错数组
Console.WriteLine($"第二个数组的第三个元素: {scores[1][2]}");  // 82

// 遍历交错数组
Console.WriteLine("交错数组内容:");
for (int i = 0; i < scores.Length; i++)
{
    Console.Write($"数组 {i}: ");
    for (int j = 0; j < scores[i].Length; j++)
    {
        Console.Write($"{scores[i][j]} ");
    }
    Console.WriteLine();
}

// 使用 foreach 遍历
Console.WriteLine("使用 foreach 遍历:");
foreach (int[] array in scores)
{
    foreach (int score in array)
    {
        Console.Write($"{score} ");
    }
    Console.WriteLine();
}

数组操作方法

Array 类的静态方法

csharp
using System;

int[] numbers = { 64, 34, 25, 12, 22, 11, 90 };
Console.WriteLine($"原数组: [{string.Join(", ", numbers)}]");

// 排序
int[] sortedNumbers = (int[])numbers.Clone();
Array.Sort(sortedNumbers);
Console.WriteLine($"排序后: [{string.Join(", ", sortedNumbers)}]");

// 反转
int[] reversedNumbers = (int[])numbers.Clone();
Array.Reverse(reversedNumbers);
Console.WriteLine($"反转后: [{string.Join(", ", reversedNumbers)}]");

// 查找元素
int index = Array.IndexOf(numbers, 25);
Console.WriteLine($"元素 25 的索引: {index}");

// 二分查找(需要先排序)
int binaryIndex = Array.BinarySearch(sortedNumbers, 25);
Console.WriteLine($"在排序数组中,25 的索引: {binaryIndex}");

// 复制数组
int[] copiedArray = new int[numbers.Length];
Array.Copy(numbers, copiedArray, numbers.Length);
Console.WriteLine($"复制的数组: [{string.Join(", ", copiedArray)}]");

// 清空数组部分元素
Array.Clear(copiedArray, 2, 3);  // 从索引2开始清空3个元素
Console.WriteLine($"清空部分元素后: [{string.Join(", ", copiedArray)}]");

// 调整数组大小
Array.Resize(ref copiedArray, 10);
Console.WriteLine($"调整大小后: [{string.Join(", ", copiedArray)}]");

数组的实用方法

csharp
static class ArrayUtils
{
    // 查找数组中的最大值
    public static T FindMax<T>(T[] array) where T : IComparable<T>
    {
        if (array.Length == 0)
            throw new ArgumentException("数组不能为空");
            
        T max = array[0];
        for (int i = 1; i < array.Length; i++)
        {
            if (array[i].CompareTo(max) > 0)
                max = array[i];
        }
        return max;
    }
    
    // 查找数组中的最小值
    public static T FindMin<T>(T[] array) where T : IComparable<T>
    {
        if (array.Length == 0)
            throw new ArgumentException("数组不能为空");
            
        T min = array[0];
        for (int i = 1; i < array.Length; i++)
        {
            if (array[i].CompareTo(min) < 0)
                min = array[i];
        }
        return min;
    }
    
    // 计算数组平均值
    public static double Average(int[] array)
    {
        if (array.Length == 0)
            return 0;
            
        long sum = 0;
        foreach (int number in array)
        {
            sum += number;
        }
        return (double)sum / array.Length;
    }
    
    // 数组去重
    public static T[] RemoveDuplicates<T>(T[] array)
    {
        var uniqueList = new List<T>();
        foreach (T item in array)
        {
            if (!uniqueList.Contains(item))
                uniqueList.Add(item);
        }
        return uniqueList.ToArray();
    }
}

// 使用示例
static void Main()
{
    int[] numbers = { 5, 2, 8, 1, 9, 3, 7, 2, 5 };
    
    Console.WriteLine($"最大值: {ArrayUtils.FindMax(numbers)}");
    Console.WriteLine($"最小值: {ArrayUtils.FindMin(numbers)}");
    Console.WriteLine($"平均值: {ArrayUtils.Average(numbers):F2}");
    
    int[] unique = ArrayUtils.RemoveDuplicates(numbers);
    Console.WriteLine($"去重后: [{string.Join(", ", unique)}]");
}

集合类型

List<T> - 动态数组

csharp
using System;
using System.Collections.Generic;

// 创建 List
List<string> fruits = new List<string>();

// 添加元素
fruits.Add("苹果");
fruits.Add("香蕉");
fruits.Add("橙子");

// 批量添加
fruits.AddRange(new string[] { "葡萄", "草莓" });

// 插入元素
fruits.Insert(1, "芒果");  // 在索引1处插入

Console.WriteLine($"水果列表: [{string.Join(", ", fruits)}]");
Console.WriteLine($"列表长度: {fruits.Count}");

// 访问元素
Console.WriteLine($"第一个水果: {fruits[0]}");
Console.WriteLine($"最后一个水果: {fruits[fruits.Count - 1]}");

// 查找元素
int index = fruits.IndexOf("香蕉");
Console.WriteLine($"香蕉的索引: {index}");

bool hasApple = fruits.Contains("苹果");
Console.WriteLine($"是否包含苹果: {hasApple}");

// 删除元素
fruits.Remove("橙子");           // 删除第一个匹配的元素
fruits.RemoveAt(0);             // 删除指定索引的元素
Console.WriteLine($"删除后: [{string.Join(", ", fruits)}]");

// 遍历 List
foreach (string fruit in fruits)
{
    Console.WriteLine($"水果: {fruit}");
}

// 排序
fruits.Sort();
Console.WriteLine($"排序后: [{string.Join(", ", fruits)}]");

// 转换为数组
string[] fruitArray = fruits.ToArray();

Dictionary<TKey, TValue> - 字典

csharp
using System.Collections.Generic;

// 创建字典
Dictionary<string, int> studentGrades = new Dictionary<string, int>();

// 添加键值对
studentGrades.Add("Alice", 95);
studentGrades.Add("Bob", 87);
studentGrades.Add("Charlie", 92);

// 使用索引器添加/修改
studentGrades["David"] = 88;    // 添加新项
studentGrades["Alice"] = 97;    // 修改现有项

// 初始化字典
Dictionary<string, string> capitals = new Dictionary<string, string>
{
    { "中国", "北京" },
    { "美国", "华盛顿" },
    { "英国", "伦敦" },
    { "法国", "巴黎" }
};

Console.WriteLine($"字典大小: {studentGrades.Count}");

// 访问元素
Console.WriteLine($"Alice 的成绩: {studentGrades["Alice"]}");

// 安全访问(避免 KeyNotFoundException)
if (studentGrades.TryGetValue("Eve", out int eveGrade))
{
    Console.WriteLine($"Eve 的成绩: {eveGrade}");
}
else
{
    Console.WriteLine("Eve 不在字典中");
}

// 检查键是否存在
if (studentGrades.ContainsKey("Bob"))
{
    Console.WriteLine($"Bob 的成绩: {studentGrades["Bob"]}");
}

// 遍历字典
Console.WriteLine("所有学生成绩:");
foreach (KeyValuePair<string, int> pair in studentGrades)
{
    Console.WriteLine($"{pair.Key}: {pair.Value}");
}

// 简化的遍历方式
foreach (var (name, grade) in studentGrades)
{
    Console.WriteLine($"{name}: {grade}");
}

// 只遍历键或值
Console.WriteLine("学生姓名:");
foreach (string name in studentGrades.Keys)
{
    Console.WriteLine(name);
}

Console.WriteLine("成绩:");
foreach (int grade in studentGrades.Values)
{
    Console.WriteLine(grade);
}

// 删除元素
studentGrades.Remove("Charlie");
Console.WriteLine($"删除 Charlie 后,字典大小: {studentGrades.Count}");

HashSet<T> - 集合

csharp
using System.Collections.Generic;

// 创建 HashSet
HashSet<int> numbers = new HashSet<int>();

// 添加元素(自动去重)
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
numbers.Add(2);  // 重复元素,不会被添加
numbers.Add(1);  // 重复元素,不会被添加

Console.WriteLine($"HashSet 内容: [{string.Join(", ", numbers)}]");
Console.WriteLine($"元素个数: {numbers.Count}");

// 批量添加
numbers.UnionWith(new int[] { 4, 5, 6, 3 });
Console.WriteLine($"批量添加后: [{string.Join(", ", numbers)}]");

// 检查元素是否存在
Console.WriteLine($"是否包含 3: {numbers.Contains(3)}");

// 集合操作
HashSet<int> otherNumbers = new HashSet<int> { 3, 4, 5, 6, 7, 8 };

// 交集
HashSet<int> intersection = new HashSet<int>(numbers);
intersection.IntersectWith(otherNumbers);
Console.WriteLine($"交集: [{string.Join(", ", intersection)}]");

// 并集
HashSet<int> union = new HashSet<int>(numbers);
union.UnionWith(otherNumbers);
Console.WriteLine($"并集: [{string.Join(", ", union)}]");

// 差集
HashSet<int> difference = new HashSet<int>(numbers);
difference.ExceptWith(otherNumbers);
Console.WriteLine($"差集: [{string.Join(", ", difference)}]");

// 对称差集
HashSet<int> symmetricDifference = new HashSet<int>(numbers);
symmetricDifference.SymmetricExceptWith(otherNumbers);
Console.WriteLine($"对称差集: [{string.Join(", ", symmetricDifference)}]");

Queue<T> - 队列

csharp
using System.Collections.Generic;

// 创建队列
Queue<string> queue = new Queue<string>();

// 入队
queue.Enqueue("第一个");
queue.Enqueue("第二个");
queue.Enqueue("第三个");

Console.WriteLine($"队列大小: {queue.Count}");

// 查看队首元素(不移除)
Console.WriteLine($"队首元素: {queue.Peek()}");

// 出队
while (queue.Count > 0)
{
    string item = queue.Dequeue();
    Console.WriteLine($"出队: {item}");
}

Console.WriteLine($"队列是否为空: {queue.Count == 0}");

// 实际应用:任务队列
Queue<Action> taskQueue = new Queue<Action>();
taskQueue.Enqueue(() => Console.WriteLine("执行任务 1"));
taskQueue.Enqueue(() => Console.WriteLine("执行任务 2"));
taskQueue.Enqueue(() => Console.WriteLine("执行任务 3"));

Console.WriteLine("执行任务队列:");
while (taskQueue.Count > 0)
{
    Action task = taskQueue.Dequeue();
    task.Invoke();
}

Stack<T> - 栈

csharp
using System.Collections.Generic;

// 创建栈
Stack<int> stack = new Stack<int>();

// 入栈
stack.Push(10);
stack.Push(20);
stack.Push(30);

Console.WriteLine($"栈大小: {stack.Count}");

// 查看栈顶元素(不移除)
Console.WriteLine($"栈顶元素: {stack.Peek()}");

// 出栈
while (stack.Count > 0)
{
    int item = stack.Pop();
    Console.WriteLine($"出栈: {item}");
}

// 实际应用:撤销操作
Stack<string> undoStack = new Stack<string>();

void PerformAction(string action)
{
    Console.WriteLine($"执行操作: {action}");
    undoStack.Push(action);
}

void Undo()
{
    if (undoStack.Count > 0)
    {
        string lastAction = undoStack.Pop();
        Console.WriteLine($"撤销操作: {lastAction}");
    }
    else
    {
        Console.WriteLine("没有可撤销的操作");
    }
}

// 使用示例
PerformAction("创建文件");
PerformAction("编辑文件");
PerformAction("保存文件");

Undo();  // 撤销保存文件
Undo();  // 撤销编辑文件

实践示例

示例 1:学生成绩管理系统

csharp
using System;
using System.Collections.Generic;
using System.Linq;

class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
    public List<int> Grades { get; set; }
    
    public Student(string name, int age)
    {
        Name = name;
        Age = age;
        Grades = new List<int>();
    }
    
    public double GetAverage()
    {
        return Grades.Count > 0 ? Grades.Average() : 0;
    }
    
    public void AddGrade(int grade)
    {
        if (grade >= 0 && grade <= 100)
            Grades.Add(grade);
    }
    
    public override string ToString()
    {
        return $"{Name} (年龄: {Age}, 平均分: {GetAverage():F1})";
    }
}

class GradeManager
{
    private List<Student> students;
    
    public GradeManager()
    {
        students = new List<Student>();
    }
    
    public void AddStudent(Student student)
    {
        students.Add(student);
    }
    
    public Student FindStudent(string name)
    {
        return students.FirstOrDefault(s => s.Name == name);
    }
    
    public void DisplayAllStudents()
    {
        Console.WriteLine("=== 所有学生信息 ===");
        foreach (var student in students)
        {
            Console.WriteLine(student);
            if (student.Grades.Count > 0)
            {
                Console.WriteLine($"  成绩: [{string.Join(", ", student.Grades)}]");
            }
        }
    }
    
    public void DisplayTopStudents(int count)
    {
        var topStudents = students
            .Where(s => s.Grades.Count > 0)
            .OrderByDescending(s => s.GetAverage())
            .Take(count);
            
        Console.WriteLine($"=== 前 {count} 名学生 ===");
        int rank = 1;
        foreach (var student in topStudents)
        {
            Console.WriteLine($"{rank}. {student}");
            rank++;
        }
    }
    
    public Dictionary<string, double> GetClassStatistics()
    {
        var stats = new Dictionary<string, double>();
        
        if (students.Count == 0)
            return stats;
            
        var allGrades = students.SelectMany(s => s.Grades).ToList();
        
        if (allGrades.Count > 0)
        {
            stats["平均分"] = allGrades.Average();
            stats["最高分"] = allGrades.Max();
            stats["最低分"] = allGrades.Min();
            stats["及格率"] = (double)allGrades.Count(g => g >= 60) / allGrades.Count * 100;
        }
        
        return stats;
    }
}

static void Main()
{
    var manager = new GradeManager();
    
    // 添加学生
    var alice = new Student("Alice", 20);
    alice.AddGrade(85);
    alice.AddGrade(92);
    alice.AddGrade(78);
    
    var bob = new Student("Bob", 19);
    bob.AddGrade(88);
    bob.AddGrade(95);
    bob.AddGrade(82);
    
    var charlie = new Student("Charlie", 21);
    charlie.AddGrade(91);
    charlie.AddGrade(87);
    charlie.AddGrade(94);
    
    manager.AddStudent(alice);
    manager.AddStudent(bob);
    manager.AddStudent(charlie);
    
    // 显示所有学生
    manager.DisplayAllStudents();
    
    // 显示前2名学生
    manager.DisplayTopStudents(2);
    
    // 显示班级统计
    var stats = manager.GetClassStatistics();
    Console.WriteLine("\n=== 班级统计 ===");
    foreach (var stat in stats)
    {
        Console.WriteLine($"{stat.Key}: {stat.Value:F2}");
    }
}

示例 2:图书管理系统

csharp
using System;
using System.Collections.Generic;
using System.Linq;

class Book
{
    public string ISBN { get; set; }
    public string Title { get; set; }
    public string Author { get; set; }
    public int Year { get; set; }
    public bool IsAvailable { get; set; }
    
    public Book(string isbn, string title, string author, int year)
    {
        ISBN = isbn;
        Title = title;
        Author = author;
        Year = year;
        IsAvailable = true;
    }
    
    public override string ToString()
    {
        string status = IsAvailable ? "可借" : "已借出";
        return $"{Title} - {Author} ({Year}) [{status}]";
    }
}

class Library
{
    private Dictionary<string, Book> books;  // ISBN -> Book
    private Dictionary<string, List<string>> borrowedBooks;  // 用户 -> ISBN列表
    private Queue<string> waitingList;  // 等待队列
    
    public Library()
    {
        books = new Dictionary<string, Book>();
        borrowedBooks = new Dictionary<string, List<string>>();
        waitingList = new Queue<string>();
    }
    
    public void AddBook(Book book)
    {
        books[book.ISBN] = book;
        Console.WriteLine($"添加图书: {book.Title}");
    }
    
    public bool BorrowBook(string isbn, string user)
    {
        if (!books.ContainsKey(isbn))
        {
            Console.WriteLine("图书不存在");
            return false;
        }
        
        var book = books[isbn];
        if (!book.IsAvailable)
        {
            Console.WriteLine($"图书 '{book.Title}' 已被借出");
            waitingList.Enqueue($"{user}:{isbn}");
            Console.WriteLine($"已将 {user} 加入等待队列");
            return false;
        }
        
        book.IsAvailable = false;
        
        if (!borrowedBooks.ContainsKey(user))
            borrowedBooks[user] = new List<string>();
            
        borrowedBooks[user].Add(isbn);
        Console.WriteLine($"{user} 成功借阅 '{book.Title}'");
        return true;
    }
    
    public bool ReturnBook(string isbn, string user)
    {
        if (!books.ContainsKey(isbn))
        {
            Console.WriteLine("图书不存在");
            return false;
        }
        
        if (!borrowedBooks.ContainsKey(user) || !borrowedBooks[user].Contains(isbn))
        {
            Console.WriteLine("该用户未借阅此图书");
            return false;
        }
        
        var book = books[isbn];
        book.IsAvailable = true;
        borrowedBooks[user].Remove(isbn);
        
        Console.WriteLine($"{user} 成功归还 '{book.Title}'");
        
        // 处理等待队列
        ProcessWaitingList(isbn);
        
        return true;
    }
    
    private void ProcessWaitingList(string isbn)
    {
        var tempQueue = new Queue<string>();
        bool found = false;
        
        while (waitingList.Count > 0 && !found)
        {
            string waitingEntry = waitingList.Dequeue();
            string[] parts = waitingEntry.Split(':');
            string waitingUser = parts[0];
            string waitingISBN = parts[1];
            
            if (waitingISBN == isbn)
            {
                BorrowBook(isbn, waitingUser);
                found = true;
            }
            else
            {
                tempQueue.Enqueue(waitingEntry);
            }
        }
        
        // 将其他等待项放回队列
        while (tempQueue.Count > 0)
        {
            waitingList.Enqueue(tempQueue.Dequeue());
        }
    }
    
    public List<Book> SearchBooks(string keyword)
    {
        return books.Values
            .Where(b => b.Title.Contains(keyword, StringComparison.OrdinalIgnoreCase) ||
                       b.Author.Contains(keyword, StringComparison.OrdinalIgnoreCase))
            .ToList();
    }
    
    public void DisplayAllBooks()
    {
        Console.WriteLine("\n=== 图书馆藏书 ===");
        foreach (var book in books.Values.OrderBy(b => b.Title))
        {
            Console.WriteLine(book);
        }
    }
    
    public void DisplayUserBooks(string user)
    {
        Console.WriteLine($"\n=== {user} 的借阅记录 ===");
        if (borrowedBooks.ContainsKey(user) && borrowedBooks[user].Count > 0)
        {
            foreach (string isbn in borrowedBooks[user])
            {
                Console.WriteLine(books[isbn]);
            }
        }
        else
        {
            Console.WriteLine("暂无借阅记录");
        }
    }
}

static void Main()
{
    var library = new Library();
    
    // 添加图书
    library.AddBook(new Book("978-0134685991", "Effective Java", "Joshua Bloch", 2017));
    library.AddBook(new Book("978-0135166307", "Clean Code", "Robert Martin", 2008));
    library.AddBook(new Book("978-0596009205", "Head First Design Patterns", "Eric Freeman", 2004));
    
    // 显示所有图书
    library.DisplayAllBooks();
    
    // 借阅图书
    library.BorrowBook("978-0134685991", "Alice");
    library.BorrowBook("978-0134685991", "Bob");  // 加入等待队列
    
    // 显示用户借阅记录
    library.DisplayUserBooks("Alice");
    
    // 搜索图书
    var searchResults = library.SearchBooks("Java");
    Console.WriteLine("\n=== 搜索结果 (Java) ===");
    foreach (var book in searchResults)
    {
        Console.WriteLine(book);
    }
    
    // 归还图书
    library.ReturnBook("978-0134685991", "Alice");
    
    // 再次显示所有图书
    library.DisplayAllBooks();
}

性能考虑

集合选择指南

csharp
// 根据使用场景选择合适的集合类型

// 1. 需要索引访问,大小固定 → 数组
int[] fixedSizeArray = new int[100];

// 2. 需要索引访问,大小可变 → List<T>
List<string> dynamicList = new List<string>();

// 3. 需要快速查找,键值对 → Dictionary<TKey, TValue>
Dictionary<string, int> keyValuePairs = new Dictionary<string, int>();

// 4. 需要唯一性,快速查找 → HashSet<T>
HashSet<int> uniqueNumbers = new HashSet<int>();

// 5. 先进先出 → Queue<T>
Queue<string> taskQueue = new Queue<string>();

// 6. 后进先出 → Stack<T>
Stack<string> undoStack = new Stack<string>();

// 7. 需要排序 → SortedDictionary<TKey, TValue> 或 SortedSet<T>
SortedDictionary<string, int> sortedDict = new SortedDictionary<string, int>();

性能比较

性能比较的示例代码:

csharp
using System.Diagnostics;

static void PerformanceComparison()
{
    const int itemCount = 1000000;
    var stopwatch = new Stopwatch();
    
    // List vs Array 性能比较
    Console.WriteLine("=== List vs Array 性能比较 ===");
    
    // Array 访问性能
    int[] array = new int[itemCount];
    stopwatch.Start();
    for (int i = 0; i < itemCount; i++)
    {
        array[i] = i;
    }
    stopwatch.Stop();
    Console.WriteLine($"Array 写入: {stopwatch.ElapsedMilliseconds} ms");
    
    // List 访问性能
    stopwatch.Restart();
    List<int> list = new List<int>(itemCount);
    for (int i = 0; i < itemCount; i++)
    {
        list.Add(i);
    }
    stopwatch.Stop();
    Console.WriteLine($"List 添加: {stopwatch.ElapsedMilliseconds} ms");
    
    // Dictionary vs List 查找性能
    Console.WriteLine("\n=== Dictionary vs List 查找性能 ===");
    
    var dictionary = new Dictionary<int, string>();
    var searchList = new List<KeyValuePair<int, string>>();
    
    // 准备数据
    for (int i = 0; i < 10000; i++)
    {
        dictionary[i] = $"Value{i}";
        searchList.Add(new KeyValuePair<int, string>(i, $"Value{i}"));
    }
    
    // Dictionary 查找
    stopwatch.Restart();
    for (int i = 0; i < 1000; i++)
    {
        var value = dictionary[5000];
    }
    stopwatch.Stop();
    Console.WriteLine($"Dictionary 查找: {stopwatch.ElapsedMilliseconds} ms");
    
    // List 查找
    stopwatch.Restart();
    for (int i = 0; i < 1000; i++)
    {
        var value = searchList.FirstOrDefault(kvp => kvp.Key == 5000).Value;
    }
    stopwatch.Stop();
    Console.WriteLine($"List 查找: {stopwatch.ElapsedMilliseconds} ms");
}

本章小结

本章详细介绍了 C# 中的数组和集合:

关键要点:

  • 数组类型:一维数组、多维数组、交错数组
  • 数组操作:Array 类的静态方法和实用工具
  • 集合类型List<T>Dictionary<TKey,TValue>HashSet<T>Queue<T>Stack<T>
  • 性能考虑:根据使用场景选择合适的数据结构

最佳实践:

  • 优先使用泛型集合而不是非泛型集合
  • 根据访问模式选择合适的集合类型
  • 注意集合的初始容量设置
  • 使用 LINQ 简化集合操作
  • 考虑线程安全性(必要时使用 ConcurrentCollection)

下一步: 在下一章中,我们将学习字符串处理,了解 C# 中字符串的各种操作方法。

延伸阅读

本站内容仅供学习和研究使用。