Get previous/next item of a given item in a List<>
List<int> listInts = new List<int>();
listInts.AddRange(new int[] { 1, 3, 5, 7, 9, 13 });
int index = listInts.IndexOf(3); //The index here would be "1"
index++; //Check first if the index is in the length
int element = listInts[index]; //element = 5
I have implemented this by Inheriting the .Net List
public class NavigationList<T> : List<T>
{
private int _currentIndex = 0;
public int CurrentIndex
{
get
{
if (_currentIndex > Count - 1) { _currentIndex = Count - 1; }
if (_currentIndex < 0) { _currentIndex = 0; }
return _currentIndex;
}
set { _currentIndex = value; }
}
public T MoveNext
{
get { _currentIndex++; return this[CurrentIndex]; }
}
public T MovePrevious
{
get { _currentIndex--; return this[CurrentIndex]; }
}
public T Current
{
get { return this[CurrentIndex]; }
}
}
Using this becomes quite easy
NavigationList<string> n = new NavigationList<string>();
n.Add("A");
n.Add("B");
n.Add("C");
n.Add("D");
Assert.AreEqual(n.Current, "A");
Assert.AreEqual(n.MoveNext, "B");
Assert.AreEqual(n.MovePrevious, "A");
Using LINQ in one line and with circular search:
Next of
YourList.SkipWhile(x => x != NextOfThisValue).Skip(1).DefaultIfEmpty( YourList[0] ).FirstOrDefault();
Previous of
YourList.TakeWhile(x => x != PrevOfThisValue).DefaultIfEmpty( YourList[YourList.Count-1]).LastOrDefault();
This is a working example (link to the fiddle)
List<string> fruits = new List<string> {"apple", "banana", "orange", "raspberry", "kiwi"};
string NextOf = "orange";
string NextOfIs;
NextOfIs = fruits.SkipWhile(x => x!=NextOf).Skip(1).DefaultIfEmpty(fruits[0]).FirstOrDefault();
Console.WriteLine("The next of " + NextOf + " is " + NextOfIs);
NextOf = "kiwi";
NextOfIs = fruits.SkipWhile(x => x!=NextOf).Skip(1).DefaultIfEmpty(fruits[0]).FirstOrDefault();
Console.WriteLine("The next of " + NextOf + " is " + NextOfIs);
string PrevOf = "orange";
string PrevOfIs;
PrevOfIs = fruits.TakeWhile(x => x!=PrevOf).DefaultIfEmpty(fruits[fruits.Count-1]).LastOrDefault();
Console.WriteLine("The prev of " + PrevOf + " is " + PrevOfIs);
PrevOf = "apple";
PrevOfIs = fruits.TakeWhile(x => x!=PrevOf).DefaultIfEmpty(fruits[fruits.Count-1]).LastOrDefault();
Console.WriteLine("The prev of " + PrevOf + " is " + PrevOfIs);
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];