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
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With