将数组转换为字典,将value作为项的索引,将key作为项本身

neu*_*v33 30 c# linq dictionary

我有一个数组,如 -

arr[0] = "Name";
arr[1] = "Address";
arr[2] = "Phone";
...
Run Code Online (Sandbox Code Playgroud)

我想创建一个Dictionary<string, int>这样的数组值将是字典键,字典值将是索引,以便我可以通过查询其名称来获取列的索引O(1).我知道这应该是相当简单的,但我无法理解它.

我试过了 -

Dictionary<string, int> myDict = arr.ToDictionary(x => x, x => indexOf(x))
Run Code Online (Sandbox Code Playgroud)

然而,这回来了 -

{(Name, 0), (Address, 0), (Phone, 0),...}
Run Code Online (Sandbox Code Playgroud)

我知道这是因为它存储了第一次出现的索引,但这不是我想要做的.

Jon*_*eet 64

您可以使用Select包含索引的重载:

var dictionary = array.Select((value, index) => new { value, index })
                      .ToDictionary(pair => pair.value, pair => pair.index);
Run Code Online (Sandbox Code Playgroud)

或使用Enumerable.Range:

var dictionary = Enumerable.Range(0, array.Length).ToDictionary(x => array[x]);
Run Code Online (Sandbox Code Playgroud)

请注意,ToDictionary如果您尝试提供两个相等的键,则会引发异常.你应该仔细考虑你的数组中有两个相等值的可能性,以及你想在那种情况下发生什么.

我会被诱惑只是手动做到这一点:

var dictionary = new Dictionary<string, int>();
for (int i = 0; i < array.Length; i++)
{
    dictionary[array[i]] = i;
}
Run Code Online (Sandbox Code Playgroud)

  • 值得注意的是,如果存在重复值,前两个将会出错.他们可能想先添加一个"Distinct". (2认同)
  • @ neuDev33第二个有拼写错误.它应该是这样的:`Enumerable.Range(0,array.Length).ToDictionary(x => array [x],x => x);` (2认同)