Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get previous/next item of a given item in a List<>

Tags:

c#

list

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#?

like image 804
NeedAnswers Avatar asked Jul 17 '14 09:07

NeedAnswers


2 Answers

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];
like image 184
Adil Avatar answered Oct 18 '22 08:10

Adil


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);
like image 31
Baro Avatar answered Oct 18 '22 06:10

Baro