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

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)