Skip to content

Instantly share code, notes, and snippets.

@CheeryLee
Created June 28, 2020 11:47
Show Gist options
  • Save CheeryLee/b1593bcd3dca4d56219f5470f8e33a13 to your computer and use it in GitHub Desktop.
Save CheeryLee/b1593bcd3dca4d56219f5470f8e33a13 to your computer and use it in GitHub Desktop.
Looped list implementation without using loop to get a value with a negative index.
using System.Collections.Generic;
public class LoopList<T> : List<T> {
public new T this[int index] {
get {
index = CalculateIndex(index);
return base[index];
}
set {
index = CalculateIndex(index);
base[index] = value;
}
}
public LoopList() { }
public LoopList(IEnumerable<T> collection) : base(collection) { }
public new void RemoveAt(int index) {
Remove(this[index]);
}
private int CalculateIndex(int index) {
if (index < 0) {
int reversedIndex = (index + 1) * -1;
if (reversedIndex >= Count) {
index = Count - 1 - (index % Count);
} else {
index = reversedIndex;
}
} else if (index >= Count) {
index %= Count;
}
return index;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment