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#?
int index = list.IndexOf(9); // find the index of the given number
// find the index of next and the previous number
// by taking into account that
// the given number might be the first or the last number in the list
int prev = index > 0 ? index - 1 : -1;
int next = index < list.Count - 1 ? index + 1 : -1;
int nextItem, prevItem;
// if indexes are valid then get the items using indexer
// otherwise set them to a temporary value,
// you can also use Nullable instead
nextItem = prev != -1 ? list[prev] : 0;
prevItem = next != -1 ? list[next] : 0;