From a list, generate a dictionary of each entry's position in the list?

78 views Asked by At

Given a list of distinct items, I want to get a dictionary lookup for each element's index in the list.

I can write this in normal code like the following:

//reference C# pseudocode
interface IThing
{
    int Id {get;}
}

...

List<IThing> things = ...; // guaranteed not to have the same id more than once

...

Dictionary<int, int> lookup = new();

for (int i = 0; i < things.Count; ++i)
    lookup[things[i].Id] = i;

I'm fairly sure this can be achieved using Linq or MoreLinq but I cannot think what it would be called to find the correct extension method. Does this algorithm have a particular name and is there something provided... the main issue being that most Linq methods do not tell you the index of the item?

1

There are 1 answers

2
Dmitry Bychenko On

Standard Linq is enough. You can try Select to obtain both item and its index followed by .ToDictionary():

Dictionary<int, int> lookup = things
  .Select((item, index) => (item, index)) // we want both item and its index
  .ToDictionary(pair => pair.item.Id,     // Key is item's id 
                pair => pair.index);      // Value is index