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

后端 未结 11 1273
余生分开走
余生分开走 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 03:55

    I have implemented this by Inheriting the .Net List

    public class NavigationList : List
        {
            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 n = new NavigationList();
                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");
    

提交回复
热议问题