数组:数量固定的同类型数据

int[] numbers = { 3, 7, 1, 9 };
Console.WriteLine(numbers[0]);        // 3,下标从 0 开始
Console.WriteLine(numbers.Length);    // 4

numbers[1] = 100;                     // 修改第 2 个元素

先声明再赋值,需要指定长度:

string[] names = new string[3];
names[0] = "小明";
names[1] = "小红";
names[2] = "小刚";

数组长度在创建后不能改变。下标越界会抛出 IndexOutOfRangeException,所以访问前先确认 下标 < 数组.Length。

List:可以随时增删的列表

数组长度固定,日常用得更多的是 List<T>。用之前先在文件顶部 using System.Collections.Generic;。

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        List<string> todo = new List<string>();

        todo.Add("买菜");
        todo.Add("写代码");
        todo.Add("跑步");

        todo.Remove("写代码");

        Console.WriteLine(todo.Count);        // 2
        Console.WriteLine(todo[0]);           // 买菜

        foreach (string item in todo)
        {
            Console.WriteLine($"- {item}");
        }
    }
}

List<T> 尖括号里的 T 是元素类型,写成 List<int>、List<double> 都可以。

常用操作:

List<int> scores = new List<int> { 88, 92, 75 };

scores.Add(60);                  // 末尾追加
scores.Insert(0, 100);           // 插到指定位置
scores.RemoveAt(0);              // 按下标删除
Console.WriteLine(scores.Count); // 元素个数
Console.WriteLine(scores.Contains(92));  // 是否存在,True
scores.Sort();                   // 升序排序
scores.Clear();                  // 清空

创建时就知道内容,可以用集合初始化器 new List<int> { 1, 2, 3 } 一步写完。

Dictionary:用键查值

需要「根据一个名字找到一份数据」时用字典。同样需要 using System.Collections.Generic;。

Dictionary<string, int> stock = new Dictionary<string, int>();

stock["苹果"] = 12;
stock["香蕉"] = 7;

Console.WriteLine(stock["苹果"]);            // 12
Console.WriteLine(stock.ContainsKey("梨"));  // False

foreach (var pair in stock)
{
    Console.WriteLine($"{pair.Key} 还剩下 {pair.Value} 个");
}

直接访问不存在的键会抛异常。先判断,或者用 TryGetValue 一次搞定:

if (stock.TryGetValue("梨", out int count))
{
    Console.WriteLine($"梨还有 {count} 个");
}
else
{
    Console.WriteLine("没有梨");
}

out int count 是 C# 的「输出参数」:方法把找到的值放进这个变量,同时返回是否找到。

字符串的常用操作

字符串本身可以看作一串字符,Length 是长度,[0] 是第一个字符:

string text = "Hello CodeNest";
Console.WriteLine(text.Length);    // 14
Console.WriteLine(text[0]);        // H

常用方法:

string s = "  码巢 CodeNest  ";

Console.WriteLine(s.Trim());                  // 去掉两端空格
Console.WriteLine(s.ToUpper());               // 转大写
Console.WriteLine(s.Contains("CodeNest"));    // 是否包含,True
Console.WriteLine(s.Replace("码巢", "CodeNest"));
Console.WriteLine(s.Substring(2, 2));         // 从下标 2 起取 2 个字符
Console.WriteLine(s.StartsWith(" "));         // 是否以某段文字开头

切分与合并:

string line = "苹果,香蕉,橘子";
string[] parts = line.Split(',');
Console.WriteLine(parts.Length);       // 3

string joined = string.Join(" / ", parts);
Console.WriteLine(joined);             // 苹果 / 香蕉 / 橘子

数字与文本互转:

int n = int.Parse("42");               // 文本转整数,格式不对会抛异常
bool ok = int.TryParse("abc", out int value);  // 更安全的做法,ok 为 False

string s1 = 42.ToString();
string s2 = 3.14159.ToString("F2");    // 保留两位小数:"3.14"

处理用户输入时优先用 TryParse,避免输入不合法直接让程序崩掉。

LINQ:像描述需求一样查询数据

using System.Linq; 之后,集合可以直接使用 Where、Select、Sum 等方法,把「筛、算、排」写成一串链式调用。

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

class Program
{
    static void Main(string[] args)
    {
        List<int> scores = new List<int> { 88, 92, 75, 60, 100 };

        var passed = scores.Where(s => s >= 60);          // 筛选
        Console.WriteLine(string.Join(", ", passed));     // 88, 92, 75, 60, 100

        Console.WriteLine(scores.Sum());                   // 415
        Console.WriteLine(scores.Max());                   // 100
        Console.WriteLine(scores.Average());               // 83

        var sorted = scores.OrderByDescending(s => s);
        Console.WriteLine(string.Join(", ", sorted));      // 100, 92, 88, 75, 60

        Console.WriteLine(scores.Count(s => s >= 90));     // 2

        var first = scores.First(s => s < 80);
        Console.WriteLine(first);                          // 75
    }
}

s => s >= 60 是 Lambda 表达式,读作「对于每个 s,返回 s 是否大于等于 60」。

只要找到第一个满足条件的元素就用 First,找不到会抛异常;不确定是否存在时用 FirstOrDefault:

var maybe = scores.FirstOrDefault(s => s > 1000);
Console.WriteLine(maybe);   // 0(int 的默认值),不会抛异常

对一组对象做查询更体现 LINQ 的价值:

class Student
{
    public string Name = string.Empty;
    public int Score;
}

static void Main(string[] args)
{
    List<Student> classA = new List<Student>
    {
        new Student { Name = "小明", Score = 92 },
        new Student { Name = "小红", Score = 78 },
        new Student { Name = "小刚", Score = 85 },
    };

    var names = classA
        .Where(s => s.Score >= 80)
        .OrderByDescending(s => s.Score)
        .Select(s => $"{s.Name}({s.Score})");

    Console.WriteLine(string.Join(",", names));   // 小明(92),小刚(85)
}

值类型与引用类型

int、double、bool、char 是值类型,赋值时复制一份,互不影响:

int a = 1;
int b = a;
b = 99;
Console.WriteLine(a);   // 1,没有被改动

数组、List、类等是引用类型,赋值时复制的是「指向同一份数据的引用」:

int[] x = { 1, 2 };
int[] y = x;
y[0] = 99;
Console.WriteLine(x[0]);   // 99,x 和 y 指向同一份数据

想复制一份互不影响的数组,用 (int[])x.Clone() 或 new List<int>(oldList)。

可空类型

值类型默认不能为「空」。确实需要表示「没有值」时,在类型后加 ?:

int? maybeAge = null;
if (maybeAge.HasValue)
{
    Console.WriteLine(maybeAge.Value);
}
else
{
    Console.WriteLine("没有填写年龄");
}

字符串是引用类型,本身就可以为 null。读取 null 字符串的成员会抛 NullReferenceException,这是最常见的运行时报错,所以字符串使用前养成判断习惯:

string name = null;
if (!string.IsNullOrEmpty(name))
{
    Console.WriteLine(name.Length);
}

下一步

  • 类型与对象:把数据和行为打包成类,写出结构清晰的项目