57 lines
2.0 KiB
C#
57 lines
2.0 KiB
C#
#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<int, IBlueRow> findRow;
|
|
readonly Func<int, bool> containsKey;
|
|
|
|
public BlueRowCollection(ICollection source, IBlueTableSchema schema, Func<int, IBlueRow>? findRow = null, Func<int, bool>? 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<int, IBlueRow> genDict) {
|
|
findRow ??= id => genDict[id];
|
|
containsKey ??= genDict.ContainsKey;
|
|
} else if (source is IReadOnlyDictionary<int, IBlueRow> roGenDict) {
|
|
findRow ??= id => roGenDict[id];
|
|
containsKey = roGenDict.ContainsKey;
|
|
} else {
|
|
var cachedRows = new Lazy<Dictionary<int, IBlueRow>>(() =>
|
|
source.Cast<IBlueRow>().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<T>.
|
|
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();
|
|
}
|