反转列表的特定部分 C#
invert a specific part of a list C#
我需要一个程序来反转两个终端之间列表的一部分。
示例:
列表:1、2、3、3、5、4
输出:1, 2, 3, 3, 4, 5(只有4和5倒置)
我找到了这个:
positionCrepe.Reverse(indexOfMaxToSearch, positionCrepe.Count);
但是不行,因为我出错了:
System.ArgumentException: The offset and length were out of bounds for this table or the number is greater than the number of index elements at the end of the source collection.
但是
indexOfMaxToSearch = 2
和
positionCrepe.count = 5
所以它不超过table
的索引
有人有解决办法吗?
谢谢。
第二个参数是您要反转多少个元素,而不是列表中有多少个元素。
因此,如果您想反转从 indexOfMaxToSearch
开始的所有内容,您需要反转 positionCrepe.Count - indexOfMaxToSearch
个元素:
positionCrepe.Reverse(indexOfMaxToSearch, positionCrepe.Count - indexOfMaxToSearch);
错误消息实际上是说第一个参数加上第二个参数超出了数组的范围。
如果你看一下 Reverse 的定义,
index:要反转的范围的从零开始的起始索引。
count:要反转的范围内的元素数。
您可以使用以下方法使其工作。计数必须小于剩余的指数
positionCrepe.Reverse(2, positionCrepe.Count - 2);
我需要一个程序来反转两个终端之间列表的一部分。 示例:
列表:1、2、3、3、5、4 输出:1, 2, 3, 3, 4, 5(只有4和5倒置)
我找到了这个:
positionCrepe.Reverse(indexOfMaxToSearch, positionCrepe.Count);
但是不行,因为我出错了:
System.ArgumentException: The offset and length were out of bounds for this table or the number is greater than the number of index elements at the end of the source collection.
但是
indexOfMaxToSearch = 2
和
positionCrepe.count = 5
所以它不超过table
的索引有人有解决办法吗? 谢谢。
第二个参数是您要反转多少个元素,而不是列表中有多少个元素。
因此,如果您想反转从 indexOfMaxToSearch
开始的所有内容,您需要反转 positionCrepe.Count - indexOfMaxToSearch
个元素:
positionCrepe.Reverse(indexOfMaxToSearch, positionCrepe.Count - indexOfMaxToSearch);
错误消息实际上是说第一个参数加上第二个参数超出了数组的范围。
如果你看一下 Reverse 的定义,
index:要反转的范围的从零开始的起始索引。
count:要反转的范围内的元素数。
您可以使用以下方法使其工作。计数必须小于剩余的指数
positionCrepe.Reverse(2, positionCrepe.Count - 2);