实战项目

C# 教程 · 第 8 章 · 6 次浏览

做一个控制台版"待办清单":添加、完成、删除、统计。把类、集合、LINQ 全部用上,是 C# 入门的最佳练习。

功能

  • 添加待办(输入文字)
  • 标记完成(按编号)
  • 删除待办
  • 显示列表 + 完成率

代码示例

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

class Todo {
    public int Id { get; set; }
    public string Text { get; set; }
    public bool Done { get; set; }
}

class Program {
    static void Main() {
        var todos = new List<Todo>();
        int nextId = 1;

        while (true) {
            Console.WriteLine("\n1.添加 2.完成 3.删除 4.显示 5.退出");
            var cmd = Console.ReadLine();

            if (cmd == "1") {
                Console.Write("内容: ");
                todos.Add(new Todo { Id = nextId++, Text = Console.ReadLine() });
            } else if (cmd == "2") {
                Console.Write("编号: ");
                int id = int.Parse(Console.ReadLine());
                todos.First(t => t.Id == id).Done = true;
            } else if (cmd == "3") {
                Console.Write("编号: ");
                int id = int.Parse(Console.ReadLine());
                todos.RemoveAll(t => t.Id == id);
            } else if (cmd == "4") {
                var done = todos.Count(t => t.Done);
                foreach (var t in todos)
                    Console.WriteLine($"{(t.Done ? "[✓]" : "[ ]")} {t.Id}. {t.Text}");
                Console.WriteLine($"完成率: {(todos.Count == 0 ? 0 : done * 100 / todos.Count)}%");
            } else break;
        }
    }
}