C# 将数组转换为字典,值作为项目的索引,键作为项目本身

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15252225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:41:57  来源:igfitidea点击:

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

c#linqdictionary

提问by neuDev33

I have an array such as -

我有一个数组,例如 -

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

I want to create a Dictionary<string, int>such that the array values will be the dictionary keys and the dictionary values will be the index, so that I can get the index of a column by querying its name in O(1). I know this should be fairly simple, but I can't get my head around it.

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

I tried -

我试过 -

Dictionary<string, int> myDict = arr.ToDictionary(x => x, x => indexOf(x))

however, this returns -

然而,这将返回 -

{(Name, 0), (Address, 0), (Phone, 0),...}

I know this happens because it is storing the index of the first occurence, but that's not what I'm looking to do.

我知道发生这种情况是因为它存储了第一次出现的索引,但这不是我想要做的。

采纳答案by Jon Skeet

You can use the overload of Selectwhich includes the index:

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

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

Or use Enumerable.Range:

或使用Enumerable.Range

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

Note that ToDictionarywill 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.

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

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;
}

回答by Hazy

Another way is:

另一种方式是:

var dictionary = arr.ToDictionary(x => Array.IndexOf(arr, x));