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#?
Following may be helpful
int NextValue = 0;
int PreviousValue =0;
int index = lstOfNo.FindIndex(nd =>nd.Id == 9);
var Next = lstOfNo.ElementAtOrDefault(index + 1);
var Previous = lstOfNo.ElementAtOrDefault(index - 1);
if (Next != null)
NextValue = Next;
if (Previous != null)
PreviousValue = Previous;
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];
To make it a kind of Circular list, try this:
public class NavigationList<T> : List<T>
{
private int _currentIndex = -1;
public int CurrentIndex
{
get
{
if (_currentIndex == Count)
_currentIndex = 0;
else if (_currentIndex > Count - 1)
_currentIndex = Count - 1;
else if (_currentIndex < 0)
_currentIndex = 0;
return _currentIndex;
}
set { _currentIndex = value; }
}
public T MoveNext
{
get { _currentIndex++; return this[CurrentIndex]; }
}
public T Current
{
get { return this[CurrentIndex]; }
}
}
Also if you want compact solution with circular logic without creating new list you can use following code:
int nextNumber = list[(list.IndexOf(currentNumber) + 1) % list.Count];
int previousNumber = list[(list.IndexOf(currentNumber) - 1 + list.Count) % list.Count];
https://dotnetfiddle.net/PkP2Jy
var index = list.IndexOf(9);
if (index == -1)
{
return; // or exception - whater, no element found.
}
int? nextItem = null; //null means that there is no next element.
if (index < list.Count - 1)
{
nextItem = list[index + 1];
}
int? prevItem = null;
if (index > 0)
{
prevItem = list[index - 1];
}