Menu
CoddyTech

Correspondência de padrões

Parte da seção Fundamentos de C# e .NET do Journey de ASP.NET Core da Coddy. Lição 14 de 20.

Padrões testam o formato de um valor com is e em switch. Padrões relacionais fazem comparações (< 0, >= 13), e and, or e not os combinam. Um padrão de tipo verifica um tipo e dá um nome ao valor. Um padrão de propriedade examina o interior de um objeto, e um padrão de lista corresponde a cada item de um array:

if (age is >= 13 and <= 19) Console.WriteLine("teen");
if (value is int n) Console.WriteLine(n + 1);
if (order is { Country: "NL", Total: > 100 }) Console.WriteLine("free shipping");
if (words is ["greet", var name]) Console.WriteLine($"Hi {name}");
if (input is null or "") Console.WriteLine("empty");

age is >= 13 and <= 19 expressa a regra que verifica e menciona age uma vez, enquanto age >= 13 && age <= 19 o menciona duas vezes. O padrão de lista corresponde apenas a um array com dois itens, cujo primeiro item é "greet".

challenge icon

Desafio

Fácil

O rastreador aceita qualquer valor, até mesmo -5. Recuse valores que não possam ser reais.

  1. No caso add, logo após o valor ser analisado, teste-o com um padrão relacional: ele deve ser maior que 0 e, no máximo, 10000.
  2. Quando não for, escreva esta linha em stderr e return 1; antes de adicionar ou salvar qualquer coisa:
    The amount must be more than 0 and at most 10000.

0, -5 e 10000.01 são recusados. 0.01 e 10000 ainda são adicionados.

Experimente: o terminal ao lado do editor já mostra dotnet run -- add Laptop 12000 work, então pressione Executar: a mensagem acima, em vermelho. Altere 12000 para 10000 e pressione Executar novamente: Added Laptop: 10000.00 (work).

Experimente você mesmo

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;
            }
            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;

Todas as lições de Fundamentos de C# e .NET