Since C# version 8, there is a new way of indexing, as shown in the example:
void Main()
{
Index idx = ^5; // counted from last to first element
var sentence = new string[]
{
"The", "quick", "brown", "fox", // position 0 ... 3
"jumped", "over", "the", "lazy", "dog" // position 4 ... 8
};
var lstSentence = sentence.ToList(); // applicable to list as well
Console.WriteLine(sentence[idx]);
Console.WriteLine(lstSentence[idx]);
}
It returns jumped
.
So far so good. But how can you get the absolute position representing ^5
efficiently ?
I saw .NET internally is using Index (which I added to this example), and there is a value property.
How can I get the position of sentence[^5]
?
Something like
var absPos = sentence[^5].Index.Value; // get absolute position (which is = 4)
(but unfortunately this doesn't seem to exist)
I know there is a formula (number of elements - position from right), but the compiler / .net calculates and probably stores this somewhere.
Update: idx.Value isn't the solution, it just stores the relative value 5 together with .IsFromEnd, which is true. But you can't access it directly, like sentence[^5].Index.Value
which is what I wanted to know.
Note: This is also useful for Dictionary
, if you take a look at the RudimentaryMultiValuedDictionary Example - if you want to add an additional indexer like public List<TValue> this[Index idx]
you will require that. internalDictionary.ElementAtOrDefault(i)
, which you need for this purpose, does only work with integer values (absolute positions).