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];
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With