#nullable enable namespace Bts.DataStreamCore; using BCG; using System; using System.Collections; using System.Collections.Generic; using System.Linq; public class BlueRowCollection : IBlueRowCollection { readonly ICollection source; readonly Func findRow; readonly Func containsKey; public BlueRowCollection(ICollection source, IBlueTableSchema schema, Func? findRow = null, Func? containsKey = null) { this.source = source; this.schema = schema; if (findRow is null || containsKey is null) { if (source is IBlueRowCollection brc) { findRow ??= id => brc[id]; containsKey ??= brc.containsID; } else if (source is IDictionary dict) { findRow ??= id => dict[id] as IBlueRow ?? throw new KeyNotFoundException(); containsKey ??= id => dict.Contains(id); } else if (source is IDictionary genDict) { findRow ??= id => genDict[id]; containsKey ??= genDict.ContainsKey; } else if (source is IReadOnlyDictionary roGenDict) { findRow ??= id => roGenDict[id]; containsKey = roGenDict.ContainsKey; } else { var cachedRows = new Lazy>(() => source.Cast().ToDictionary(r => r.Id())); findRow ??= id => cachedRows.Value[id]; // Don't remove this lambda expression. Intellisense may suggest it, but that would // instantiate 'cachedRows' immediately and defeat the purpose of using Lazy. containsKey ??= id => cachedRows.Value.ContainsKey(id); } } this.findRow = findRow; this.containsKey = containsKey; } public IBlueRow this[int id] => findRow(id); public IBlueTableSchema schema { get; } public int Count => source.Count; public bool containsID(int id) => containsKey(id); public IEnumerator GetEnumerator() => source.GetEnumerator(); }