将数组转换为字典,其值作为项目的索引,键作为项目本身 [英] Convert an array to dictionary with value as index of the item and key as the item itself

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

问题描述

我有一个数组,如 -

  arr [0] =Name; 
arr [1] =地址;
arr [2] =电话;
...

我想创建一个字典< string ,int> ,使得数组值将是字典键,字典值将是索引,以便我可以通过在中查询其名称来获取列的索引O(1)。我知道这应该是相当简单的,但我不能让我的头脑。



我试过 -

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

然而,这将返回 -

  {(Name,0),(Address,0),(Phone,0) 。$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ 

我知道这是因为它存储第一次发生的索引,但这不是什么我想要做。

解决方案

可以使用的重载选择其中包括索引:

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

或使用 Enumerable.Range p>

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

请注意, ToDictionary 会抛出异常if您尝试提供两个相等的键。您应该仔细考虑阵列中有两个相等值的可能性,以及在这种情况下想要发生的情况。



我会被诱惑它手动地:

  var dictionary = new Dictionary< string,int>(); (int i = 0; i  {
dictionary [array [i]] = i;
}


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.

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.

解决方案

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

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

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