Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a map of list element indices using Linq

Tags:

c#

sorting

linq

I want to take a List, and generate a Dictionary which maps each element to its index in the List. I can do this like so, for a List<string>:

var myList = new List<string>{ /* populate list */ };
var orderMap = new Dictionary<string, int>();

foreach (var element in myList)
{
    orderMap[element] = myList.IndexOf(element);
}

Basically, I want to take a list like:

Apple
Banana
Orange

And return a map showing indices:

Apple -> 0
Banana -> 1
Orange -> 2

How can I do this with Linq? I think something like this should work:

orderMap = myList.Select( x => /* return a key value pair mapping x to myList.IndexOf(x) */ );

But I can't figure out the right syntax for it. Besides, can you refer to the list itself in the delegate used for Select?

like image 783
Superbest Avatar asked Dec 12 '12 07:12

Superbest


1 Answers

While you can refer to the list within the delegate, it's not generally a good idea. You really want to use the overload of Select which provides the index as well as the value:

var dictionary = list.Select((value, index) => new { value, index })
                     .ToDictionary(p => p.value, p => p.index);

Note that this will throw an exception if you have any duplicate elements.

like image 194
Jon Skeet Avatar answered Nov 03 '22 01:11

Jon Skeet