using System.Collections.Immutable; using System.Text.Json; namespace Yuanshen.Common.Data.Excel; public sealed class ExcelTable { private readonly ImmutableArray _items; private readonly ImmutableDictionary _itemsById; public ExcelTable(JsonDocument document, Type type) { ImmutableArray.Builder items = ImmutableArray.CreateBuilder(); foreach (JsonElement element in document.RootElement.EnumerateArray()) { if (element.ValueKind != JsonValueKind.Object) throw new ArgumentException("Excel table root must be an array of objects"); items.Add((element.Deserialize(type) as ExcelItem)!); } _items = items.ToImmutable(); _itemsById = _items.ToImmutableDictionary(item => item.ExcelId); } public IReadOnlyList Items => _items; public TExcel? GetById(uint id) where TExcel : ExcelItem => _itemsById.TryGetValue(id, out ExcelItem? item) ? item as TExcel : null; }