Skip to content

Instantly share code, notes, and snippets.

@ggppjj
Created November 25, 2024 19:37
Show Gist options
  • Save ggppjj/9b8e64881d1d01b5b4b54ee8de97bf61 to your computer and use it in GitHub Desktop.
Save ggppjj/9b8e64881d1d01b5b4b54ee8de97bf61 to your computer and use it in GitHub Desktop.
/// <summary>
/// A list that provides both zero-indexed and one-indexed access to its elements.
/// </summary>
/// <typeparam name="T">The type of elements in the list.</typeparam>
public class NormalizableList<T> : IList<T>
{
private readonly IList<T> _innerList;
public NormalizableList() => _innerList = new List<T>();
public NormalizableList(IEnumerable<T> collection) =>
_innerList = new List<T>(collection);
public ZeroIndexedList ZeroIndexed => new(_innerList);
public OneIndexedList OneIndexed => new(_innerList);
public T this[int index]
{
get => _innerList[index];
set => _innerList[index] = value;
}
public int Count => _innerList.Count;
public bool IsReadOnly => _innerList.IsReadOnly;
public void Add(T item) => _innerList.Add(item);
public void Clear() => _innerList.Clear();
public bool Contains(T item) => _innerList.Contains(item);
public void CopyTo(T[] array, int arrayIndex) => _innerList.CopyTo(array, arrayIndex);
public IEnumerator<T> GetEnumerator() => _innerList.GetEnumerator();
public int IndexOf(T item) => _innerList.IndexOf(item);
public void Insert(int index, T item) => _innerList.Insert(index, item);
public bool Remove(T item) => _innerList.Remove(item);
public void RemoveAt(int index) => _innerList.RemoveAt(index);
IEnumerator IEnumerable.GetEnumerator() => _innerList.GetEnumerator();
/// <summary>
/// Provides zero-indexed access to the elements of the list.
/// Mostly here for disambiguation.
/// </summary>
public class ZeroIndexedList
{
private readonly IList<T> _innerList;
public ZeroIndexedList(IList<T> innerList) => _innerList = innerList;
public T this[int index]
{
get => _innerList[index];
set => _innerList[index] = value;
}
}
/// <summary>
/// Provides one-indexed access to the elements of the list.
/// </summary>
public class OneIndexedList
{
private readonly IList<T> _innerList;
public OneIndexedList(IList<T> innerList) => _innerList = innerList;
public T this[int index]
{
get
{
if (index <= 0 || index > _innerList.Count)
throw new ArgumentOutOfRangeException(
nameof(index),
"Index must be greater than 0 and less than or equal to the number of elements in the list."
);
return _innerList[index - 1];
}
set
{
if (index <= 0 || index > _innerList.Count)
throw new ArgumentOutOfRangeException(
nameof(index),
"Index must be greater than 0 and less than or equal to the number of elements in the list."
);
_innerList[index - 1] = value;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment