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

标签 c# linq dictionary

我有一个数组,例如 -

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

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

我试过了-

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

但是,这会返回 -

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

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

最佳答案

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

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

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

不过,我很想手动完成:

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

关于c# - 将数组转换为字典,值作为项目的索引,键作为项目本身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15252225/

相关文章:

c# - 有没有办法将 pdb 文件与 ilmerge 合并?

c# - 如何选择多个具有相似名称的 XML 子节点

c# - 升级到 RC 后,具有多对多关系的实体创建失败

c# - LINQ 风格的 IS IN 查询

Python 基类方法调用 : unexpected behavior

c# - Windows 应用商店应用程序中所有页面的通用 Xaml

linq - Entity Framework /IQueryable 中的交叉连接语法

c# - 您更喜欢 'materializing' IEnumerables?

python - Numpy:根据字典转换一维数组中的值

dictionary - 初始化 map 时如何设置容量可以防止重新哈希