反转列表的特定部分 C#

Izo*_*Izo 1 c# loops list panel

我需要一个程序来反转两个终端之间的部分列表。例子 :

List: 1, 2, 3, 3, 5, 4 输出: 1, 2, 3, 3, 4, 5 (只有4和5取反)

我找到了这个:

                positionCrepe.Reverse(indexOfMaxToSearch, positionCrepe.Count);
Run Code Online (Sandbox Code Playgroud)

但它不起作用,因为我有一个错误:

System.ArgumentException: 偏移量和长度超出此表的范围或数量大于源集合末尾的索引元素数。

然而

indexOfMaxToSearch = 2

positionCrepe.count = 5

所以它不超过表的索引

有人有解决方案吗?谢谢你。

Swe*_*per 6

第二个参数是您想要反转的元素数量,而不是列表中的元素数量。

因此,如果您想反转从 开始的所有内容indexOfMaxToSearch,您需要反转positionCrepe.Count - indexOfMaxToSearch元素:

positionCrepe.Reverse(indexOfMaxToSearch, positionCrepe.Count - indexOfMaxToSearch);
Run Code Online (Sandbox Code Playgroud)

错误消息实际上是说第一个参数加上第二个参数超出了数组的范围。

  • @JonathonChase 不,它是 [`List.Reverse`](https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.reverse?view=netframework-4.8#System_Collections_Generic_List_1_Reverse_System_Int32_System_Int32_ ) (2认同)