ReadOnlySelectorWrapper for IList
This commit is contained in:
1 parent
db135a36d9
commit
0cee53e287
1 file changed
+53
@@ -158,6 +158,9 @@ namespace bts.collections {
|
||||
public static IReadOnlyList<TResult> WrapSelectorRO<T, TResult>(this IList<T> list, Func<T, TResult> convert) =>
|
||||
new SelectorWrapper<T, TResult>(list, convert, null);
|
||||
|
||||
public static IReadOnlyList<TResult> WrapReadOnlySelector<T, TResult>(this IReadOnlyList<T> list, Func<T, TResult> convert) =>
|
||||
new ReadOnlySelectorWrapper<T, TResult>(list, convert);
|
||||
|
||||
private static Random rng = new Random();
|
||||
|
||||
public static void Shuffle<T>(this IList<T> list) {
|
||||
@@ -374,6 +377,56 @@ namespace bts.collections {
|
||||
}
|
||||
}
|
||||
|
||||
class ReadOnlySelectorWrapper<TIn, TOut> : IReadOnlyList<TOut>, IList<TOut> {
|
||||
readonly IReadOnlyList<TIn> _source;
|
||||
readonly Func<TIn, TOut> _convert;
|
||||
|
||||
public ReadOnlySelectorWrapper(IReadOnlyList<TIn> source, Func<TIn, TOut> convert) {
|
||||
_source = source;
|
||||
_convert = convert;
|
||||
}
|
||||
|
||||
public TOut this[int index] {
|
||||
get => _convert(_source[index]);
|
||||
set => throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public int Count => _source.Count;
|
||||
|
||||
public bool IsReadOnly => true;
|
||||
|
||||
public void Add(TOut item) => throw new NotSupportedException();
|
||||
public void Clear() => throw new NotSupportedException();
|
||||
|
||||
public bool Contains(TOut item) =>
|
||||
IndexOf(item) >= 0;
|
||||
|
||||
public void CopyTo(TOut[] array, int arrayIndex) {
|
||||
int stop = _source.Count;
|
||||
for (int i = 0; i < stop; i++)
|
||||
array[i + arrayIndex] = _convert(_source[i]);
|
||||
}
|
||||
|
||||
public IEnumerator<TOut> GetEnumerator() {
|
||||
for (int i = 0; i < _source.Count; i++)
|
||||
yield return _convert(_source[i]);
|
||||
}
|
||||
IEnumerator IEnumerable.GetEnumerator() =>
|
||||
GetEnumerator();
|
||||
|
||||
public int IndexOf(TOut item) {
|
||||
for (int i = 0; i < _source.Count; i++) {
|
||||
if (EqualityComparer<TOut>.Default.Equals(_convert(_source[i]), item))
|
||||
return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public void Insert(int index, TOut item) => throw new NotSupportedException();
|
||||
public bool Remove(TOut item) => throw new NotImplementedException();
|
||||
public void RemoveAt(int index) => throw new NotImplementedException();
|
||||
}
|
||||
|
||||
class SelectorWrapper<T> : IList<T>, IList, IReadOnlyList<T> {
|
||||
readonly Func<object, T> _convert;
|
||||
readonly Func<T, object> _convert_back;
|
||||
|
||||
Reference in new issue
Block a user