获取列表中的给定项目的上一个/下一个项目<>

时间:2014-07-17 09:33:07

标签: c# list

说我有这个清单:1,3,5,7,9,13

例如,给定值为:9,前一项为7,下一项为13

我如何使用C#实现这一目标?

12 个答案:

答案 0 :(得分:24)

您可以使用 indexer 来获取所需索引的元素。将一个添加到索引将获得 next 并从索引中减去一个将为您提供之前的元素。

int index = 4; 
int prev = list[index-1];
int next = list[index+1];

您必须检查下一个和上一个索引是否存在,否则您将获得IndexOutOfRangeException异常。由于List是零基础索引,因此第一个元素将具有索引0,第二个元素将具有1,依此类推。

if(index - 1 > -1)
   prev = list[index-1];
if(index + 1 < list.Length)
   next = list[index+1];

答案 1 :(得分:5)

        List<int> listInts = new List<int>();
        listInts.AddRange(new int[] { 1, 3, 5, 7, 9, 13 });
        int index = listInts.IndexOf(3); //The index here would be "1"
        index++; //Check first if the index is in the length
        int element = listInts[index]; //element = 5

答案 2 :(得分:5)

我通过继承.Net列表

实现了这一点
public class NavigationList<T> : List<T>
    {
        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]; }
        }
    }

使用它变得非常容易

 NavigationList<string> n = new NavigationList<string>();
            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");

答案 3 :(得分:3)

int index = list.IndexOf(9); // find the index of the given number

// find the index of next and the previous number
// by taking into account that 
// the given number might be the first or the last number in the list
int prev = index > 0 ? index - 1 : -1;

int next = index < list.Count - 1 ? index + 1 : -1;

int nextItem, prevItem;

// if indexes are valid then get the items using indexer 
// otherwise set them to a temporary value, 
// you can also use Nullable<int> instead
nextItem = prev != -1 ? list[prev] : 0;
prevItem = next != -1 ? list[next] : 0;

答案 4 :(得分:3)

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];
}

答案 5 :(得分:3)

在一行中使用LINQ并进行循环搜索:

下一个

rm -R node_modules/
rm yarn.lock
yarn install

上一个

YourList.SkipWhile(x => x != NextOfThisValue).Skip(1).DefaultIfEmpty( YourList[0] ).FirstOrDefault();

这是一个有效的示例(link to the fiddle)

YourList.TakeWhile(x => x != PrevOfThisValue).DefaultIfEmpty( YourList[YourList.Count-1]).LastOrDefault();

答案 6 :(得分:2)

以下可能会有所帮助

 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;

答案 7 :(得分:1)

这是结合 @Thunder@Melad 答案获得的完整圈子列表:

private class CircularList<T> : List<T>
    {
        private int _currentIndex = 0;
        public int CurrentIndex
        {
            get
            {
                if (_currentIndex > Count - 1) { _currentIndex = 0; }
                if (_currentIndex < 0) { _currentIndex = Count - 1; }
                return _currentIndex;
            }
            set => _currentIndex = value;
        }
        
        public int NextIndex
        {
            get
            {
                if (_currentIndex == Count - 1) return 0;
                return _currentIndex + 1;
            }
        }
        
        public int PreviousIndex
        {
            get
            {
                if (_currentIndex == 0) return Count - 1;
                return _currentIndex - 1;
            }
        }
        
        public T Next => this[NextIndex];

        public T Previous => this[PreviousIndex];

        public T MoveNext
        {
            get { _currentIndex++; return this[CurrentIndex]; }
        }

        public T MovePrevious
        {
            get { _currentIndex--; return this[CurrentIndex]; }
        }

        public T Current => this[CurrentIndex];
        
        
    }
}

check git-repo with example here

答案 8 :(得分:0)

要使其成为一种循环列表,请尝试:

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]; }
    }
}

答案 9 :(得分:0)

可以使用LinkedList<T>

完成此操作
List<int> intList = new List<int> { 1, 3, 5, 7, 9, 13 };

LinkedList<int> intLinkedList = new LinkedList<int>(intList);

Console.WriteLine("Next Value to 9 "+intLinkedList.Find(9).Next.Value);

Console.WriteLine("Next Value to 9 " +intLinkedList.Find(9).Previous.Value);

//Consider using dictionary for frequent use
var intDictionary = intLinkedList.ToDictionary(i => i, i => intLinkedList.Find(i));    

Console.WriteLine("Next Value to 9 " + intDictionary[9].Next.Value);

Console.WriteLine("Next Value to 9 " + intDictionary[9].Previous.Value);

Console.Read();

答案 10 :(得分:0)

使用ElementOrDefault()

进行操作

https://dotnetfiddle.net/fxVo6T

int?[] items = { 1, 3, 5, 7, 9, 13  };
for (int i = 0; i < items.Length; i++)
{
    int? previous = items.ElementAtOrDefault(i - 1);
    int? current = items.ElementAtOrDefault(i);
    int? next = items.ElementAtOrDefault(i + 1);
}

答案 11 :(得分:0)

此外,如果您希望使用循环逻辑的紧凑型解决方案而不创建新列表,则可以使用以下代码:

int nextNumber = list[(list.IndexOf(currentNumber) + 1) % list.Count];
int previousNumber = list[(list.IndexOf(currentNumber) - 1 + list.Count) % list.Count];

https://dotnetfiddle.net/PkP2Jy