开发者

Collection with Next()

开发者 https://www.devze.com 2023-04-12 01:28 出处:网络
How can I get next element of element to which I have reference in some collection e.g. List<T> ?

How can I get next element of element to which I have reference in some collection e.g. List<T> ?

I am not talk开发者_运维知识库ing about any loops, etc. I want get just one next (or previous) element


A collection does not have the a concept of "current element". Iterators/Enumerators do. And they have a MoveNext() method. And then you can access the current element of that enumerator with Current.

You can call GetEnumerator() on almost all collections to get an enumerator.

One problem with enumerators is you usually can't copy them nor move them backwards. (Unlike C++ where most collections have more powerful iterators)


It's not the most performant, but it should work. You can even make it an extension method.

    public static T GetNext<T>(IList<T> collection, T value )
    {
        int nextIndex = collection.IndexOf(value) + 1;
        if (nextIndex < collection.Count)
        {
            return collection[nextIndex];
        }
        else
        {
            return value; //Or throw an exception
        }
    }

And you use it like this:

        var list = new List<string> {"A", "B", "C", "D"};
        string current = "B";
        string next = GetNext(list, current);
        Console.WriteLine(next); //Prints C


To get "next" you need a concept of "current". C# doesn't use iterators like C++ does, you can either get an enumerator:

        var enumerator = x.GetEnumerator();

        while (enumerator.MoveNext())
        {
            Console.WriteLine(enumerator.Current);
        }

But it would be easier to just use an int indexer into the List<T>

0

精彩评论

暂无评论...
验证码 换一张
取 消