Get previous/next item of a given item in a List<>

后端 未结 11 1303
余生分开走
余生分开走 2021-02-12 03:18

Says I have this List : 1, 3, 5, 7, 9, 13

For example, given value is : 9, the previous item is 7 and the next item is 13

How can I achieve this using C#?

11条回答
  •  南旧
    南旧 (楼主)
    2021-02-12 04:14

    You can use indexer to get element at desired index. Adding one to index will get you next and subtracting one from index will give you previous element.

    int index = 4; 
    int prev = list[index-1];
    int next = list[index+1];
    

    You will have to check if next and previous index exists other wise you will get IndexOutOfRangeException exception. As List is zero based index so first element will have index 0 and second will have 1 and so on.

    if(index - 1 > -1)
       prev = list[index-1];
    if(index + 1 < list.Length)
       next = list[index+1];
    

提交回复
热议问题