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

后端 未结 11 1269
余生分开走
余生分开走 2021-02-12 03:18

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

相关标签:
11条回答
  • 2021-02-12 04:12

    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;
    
    0 讨论(0)
  • 2021-02-12 04:14

    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];
    
    0 讨论(0)
  • 2021-02-12 04:16

    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]; }
        }
    }
    
    0 讨论(0)
  • 2021-02-12 04:17

    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

    0 讨论(0)
  • 2021-02-12 04:19
    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];
    }
    
    0 讨论(0)
提交回复
热议问题