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#?
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];