2

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?

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Mr. Boy
  • 60,845
  • 93
  • 320
  • 589
  • What is wrong with the above code? It is easy to understand and clean way than writing complex linq query, iterating twice to fill the dictionary. I guess your way is better than a linq. – Prasad Telkikar Mar 27 '23 at 15:34

2 Answers2

4

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
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • 1
    Wow I had no idea you could do that so easily. I used to make an iterator outside the select and `++` it inside the select. Great trick to be able to do it this way. – Emperor Eto Mar 27 '23 at 18:06
  • 1
    I also did not know `Select` could know the index - thanks, – Mr. Boy Mar 28 '23 at 11:43
-3

You can use the IndexOf property of a List object to get the index of an item in it. Check code below on how to add the item name and its index to a dictionary.

  var list = new List<string>
        {
            "Texas",
            "Detroit",
            "California",
            "New York"
        };
        //declare a new dictionary to hold the item and its index
        var dict = new Dictionary<string, int>();
        foreach (var item in list)
        {
            dict.Add(item, list.IndexOf(item));
        }
Son of Man
  • 1,213
  • 2
  • 7
  • 27