todo_json.cs en C#
Una lista de tareas que sobrevive reinicios: JSON de entrada, JSON de salida.
// todo_json: lista mínima de tareas guardada como JSON en el dir temporal
using System.Text.Json;
var path = Path.Combine(Path.GetTempPath(), "todo.json");
var opts = new JsonSerializerOptions { WriteIndented = true };
var items = File.Exists(path)
? JsonSerializer.Deserialize<List<Item>>(File.ReadAllText(path), opts)
: new List<Item>();
items.Add(new Item("write the report", false));
items.Add(new Item("ship the release", false));
items[0] = items[0] with { Done = true };
File.WriteAllText(path, JsonSerializer.Serialize(items, opts));
var reloaded = JsonSerializer.Deserialize<List<Item>>(
File.ReadAllText(path), opts);
foreach (var item in reloaded)
{
var mark = item.Done ? "x" : " ";
Console.WriteLine($"[{mark}] {item.Title}");
}
Console.WriteLine($"{reloaded.Count(i => !i.Done)} open");
File.Delete(path);
record Item(string Title, bool Done);
Cómo funciona
- El archivo se carga si existe; si no, lo suple una lista nueva.
withmarca una tarea como hecha sin mutar el record.- El viaje de ida y vuelta por disco prueba que la persistencia funciona.
Palabras clave y builtins usados aquí
boolfalseforeachinnewrecordstringtrueusingvarwith
El intento, en números
- Líneas
- 27
- Caracteres a escribir
- 864
- Tokens
- 199
- Ritmo de tres estrellas
- 90 tpm
Al ritmo de tres estrellas de 90 tokens por minuto, este intento toma unos 133 segundos.
Paso 2 de 2 en Bis; paso 17 de 17 en La biblioteca de .NET.