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#?
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 fruits = new List {"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);