由于我们可以使用%
(它返回整数除法的余数)取模运算符来循环遍历索引范围,因此无需跟踪溢出情况。它将始终返回集合中的有效索引,并在到达末尾时回到0
(对于多次超过列表末尾的情况也适用):
List<int> list = new List<int> {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
List<int> newList = new List<int>();
for (int skip = 9, take = 2; take > 0; skip++, take--)
{
newList.Add(list[skip % list.Count]);
}
Result:
// newList == { 10, 1 }
![enter image description here](https://istack.dev59.com/TZf0X.webp)
This could be extracted into an extension method:
public static List<T> SkipTakeWrap<T>(this List<T> source, int skip, int take)
{
var newList = new List<T>();
while (take > 0)
{
newList.Add(source[skip % source.Count]);
skip++;
take--;
}
return newList;
}
然后它可以这样调用:
List<int> list = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
List<int> newList = list.SkipTakeWrap(9, 2);