转换一个数组值字典作为项目的指标和关键的项目本身 [英] Convert an array to dictionary with value as index of the item and key as the item itself

查看:130
本文介绍了转换一个数组值字典作为项目的指标和关键的项目本身的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,例如 -

I have an array such as -

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



我想创建一个词典<字符串,INT> 使得阵列值将是字典键和字典中的值将是指数,这样我可以在查询其名字来取得列的索引O(1)。我知道这应该是相当简单的,但我不能让我的头周围

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> 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.

推荐答案

您可以使用选择其中包括指数:

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



或者使用 Enumerable.Range

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



注意 ToDictionary 将抛出如有异常请您尽量提供两个相等的钥匙。你应该仔细考虑你的阵列有它两个相等的值,你想在那种情况下发生的事情的可能性。

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

这篇关于转换一个数组值字典作为项目的指标和关键的项目本身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆