How can I get next element of element to which I have reference in some collection e.g. List<T>
?
I am not talking about any loops, etc. I want get just one next (or previous) element
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