集合与泛型

C# 教程 · 第 5 章 · 7 次浏览

C# 集合在 System.Collections.Generic 命名空间,泛型让集合类型安全。LINQ 则让数据查询像写 SQL 一样简洁。

常用集合

  • List<T>:动态数组,最常用
  • Dictionary<K, V>:键值对
  • HashSet<T>:不重复集合
  • Queue<T> / Stack<T>:队列/栈

泛型方法

T 占位类型:T Max<T>(T a, T b) where T : IComparable。

LINQ 简介

using System.Linq 后,集合可以用 Where、Select、OrderBy 链式查询,lambda 表达式做条件。

代码示例

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

class Program {
    static void Main() {
        var nums = new List<int> { 5, 2, 8, 1, 9, 3 };

        // LINQ 查询
        var evens = nums.Where(n => n % 2 == 0);          // 偶数
        var sorted = nums.OrderBy(n => n);                // 排序
        var max = nums.Max();                              // 最大值

        Console.WriteLine("偶数: " + string.Join(",", evens));
        Console.WriteLine("排序: " + string.Join(",", sorted));
        Console.WriteLine($"最大值: {max}");

        // Dictionary
        var scores = new Dictionary<string, int> {
            { "语文", 90 }, { "数学", 95 }
        };
        Console.WriteLine($"数学: {scores["数学"]}");
    }
}