Menu
CoddyTech

Biểu thức switch

Thuộc phần C# và .NET cơ bản trong hành trình ASP.NET Core của Coddy. Bài học 15 trên 20.

Biểu thức switch chọn một giá trị bằng cách so khớp các mẫu. Giá trị đứng trước, tiếp theo là switch, rồi đến các nhánh có dạng pattern => result, ngăn cách bằng dấu phẩy. Các nhánh được thử từ trên xuống dưới và nhánh khớp đầu tiên sẽ được chọn. _ khớp với mọi thứ, vì vậy nó nằm cuối cùng:

var text = status switch
{
    200 => "OK",
    404 => "Not Found",
    >= 500 => "Server Error",
    _ => "Other",
};

Nếu không có _, trình biên dịch sẽ cảnh báo (CS8509) rằng một số giá trị không có nhánh tương ứng, và khi gặp giá trị như vậy, chương trình sẽ ném SwitchExpressionException trong lúc chạy. Câu lệnh switch chạy code cho từng trường hợp; biểu thức switch tạo ra một giá trị mà bạn có thể lưu trữ hoặc in ra.

challenge icon

Thử thách

Dễ

Thêm lệnh help để giải thích từng lệnh bằng biểu thức switch.

  1. Thêm case "help": phía trên default:. Chủ đề là args[1], hoặc "" nếu không có.
  2. Gán giá trị cho help bằng biểu thức switch trên chủ đề, mỗi nhánh nằm trên một dòng như bên dưới, rồi in giá trị đó ra:
    ""            Type help <command>, such as help add.
    "add"         add <name> <amount> [category]: saves an expense
    "remove"      remove <name>: deletes the first expense with that name
    "list"        list [category]: shows the saved expenses
    "top"         top [n]: shows the n biggest expenses, 3 by default
    "categories"  categories: shows the total of each category
  3. Nhánh cuối cùng, _, trả về No help for fly. với chủ đề thay cho fly.

Thử nhé: terminal bên cạnh trình soạn thảo đã có sẵn dotnet run -- help add, vậy hãy nhấn Chạy: add <name> <amount> [category]: saves an expense. Đổi đối số thành help fly rồi nhấn Chạy lần nữa: No help for fly. Chỉ nhập help thì bạn sẽ thấy Type help <command>, such as help add.

Tự làm thử

using System.Globalization;
using System.Text.Json;

var file = "expenses.json";
var expenses = new List<Expense>();
if (File.Exists(file))
{
    expenses = JsonSerializer.Deserialize<List<Expense>>(File.ReadAllText(file)) ?? new List<Expense>();
}
var budgets = new Dictionary<string, decimal>();
if (File.Exists("budgets.json"))
{
    budgets = JsonSerializer.Deserialize<Dictionary<string, decimal>>(File.ReadAllText("budgets.json")) ?? new Dictionary<string, decimal>();
}
var count = expenses.Count;
var total = expenses.Sum(e => e.Amount);

if (args.Length == 0)
{
    Console.WriteLine("Expense Tracker");
    Console.WriteLine($"{count} expenses");
    Console.WriteLine($"Total: {total:F2}");
}
else
{
    switch (args[0])
    {
        case "add":
            if (args.Length < 3)
            {
                Console.Error.WriteLine("Usage: add <name> <amount> [category]");
                return 1;
            }
            if (!decimal.TryParse(args[2], CultureInfo.InvariantCulture, out var amount))
            {
                Console.Error.WriteLine($"Invalid amount: {args[2]}");
                return 1;
            }
            if (amount is <= 0 or > 10000)
            {
                Console.Error.WriteLine("The amount must be more than 0 and at most 10000.");
                return 1;
            }
            var category = args.Length > 3 ? args[3] : "other";
            var expense = new Expense(args[1], amount, category);
            expenses.Add(expense);
            File.WriteAllText(file, JsonSerializer.Serialize(expenses));
            Console.WriteLine($"Added {expense.Name}: {expense.Amount:F2} ({expense.Category})");
            if (budgets.TryGetValue(category, out var limit))
            {
                var spent = expenses.Where(e => e.Category == category).Sum(e => e.Amount);
                if (spent > limit)
                {
                    Console.WriteLine($"Over budget for {category}: {spent:F2} of {limit:F2}");
                }
            }
            break;
        case "remove":
            if (args.Length < 2)
            {
                Console.Error.WriteLine("Usage: remove <name>");
                return 1;
            }
            Expense? match = expenses.Find(e => e.Name == args[1]);
            if (match is null)
            {
                Console.Error.WriteLine($"No expense named {args[1]}.");
                return 1;
            }
            expenses.Remove(match);
            File.WriteAllText(file, JsonSerializer.Serialize(expenses));
            Console.WriteLine($"Removed {match.Name}: {match.Amount:F2}");
            break;
        case "list":
            var shown = args.Length > 1 ? expenses.Where(e => e.Category == args[1]).ToList() : expenses;
            if (shown.Count == 0)
            {
                Console.WriteLine("No expenses.");
                break;
            }
            foreach (var line in shown.Select(e => $"{e.Name}: {e.Amount:F2} ({e.Category})"))
            {
                Console.WriteLine(line);
            }
            break;
        case "top":
            var howMany = 3;
            if (args.Length > 1 && !int.TryParse(args[1], out howMany))
            {
                Console.Error.WriteLine($"Invalid number: {args[1]}");
                return 1;
            }
            var biggest = expenses.OrderByDescending(e => e.Amount).Take(howMany);
            foreach (var line in biggest.Select((e, i) => $"{i + 1}. {e.Name}: {e.Amount:F2} ({e.Category})"))
            {
                Console.WriteLine(line);
            }
            break;
        case "categories":
            var groups = expenses.GroupBy(e => e.Category).OrderByDescending(g => g.Sum(e => e.Amount));
            foreach (var g in groups)
            {
                Console.WriteLine($"{g.Key}: {g.Sum(e => e.Amount):F2} ({g.Count()})");
            }
            break;
        default:
            Console.Error.WriteLine($"Unknown command: {args[0]}");
            return 1;
    }
}
return 0;
quiz iconTự kiểm tra

Bài học này có một bài trắc nghiệm ngắn. Bắt đầu bài học để trả lời và theo dõi tiến độ.

Tất cả bài học trong C# và .NET cơ bản