Convert an array to dictionary with value as index of the item and key as the item itself

前端 未结 2 1944
忘掉有多难
忘掉有多难 2020-12-05 13:21

I have an array such as -

arr[0] = \"Name\";
arr[1] = \"Address\";
arr[2] = \"Phone\";
...

I want to create a Dictionary

相关标签:
2条回答
  • 2020-12-05 13:38

    You can use the overload of Select which includes the index:

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

    Or use Enumerable.Range:

    var dictionary = Enumerable.Range(0, array.Length).ToDictionary(x => array[x]);
    

    Note that ToDictionary will throw an exception if you try to provide two equal keys. You should think carefully about the possibility of your array having two equal values in it, and what you want to happen in that situation.

    I'd be tempted just to do it manually though:

    var dictionary = new Dictionary<string, int>();
    for (int i = 0; i < array.Length; i++)
    {
        dictionary[array[i]] = i;
    }
    
    0 讨论(0)
  • 2020-12-05 13:41

    Another way is:

    var dictionary = arr.ToDictionary(x => Array.IndexOf(arr, x));
    
    0 讨论(0)
提交回复
热议问题