Created
June 28, 2020 11:47
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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