如何通过Key in Dictionary获得价值

问题描述 投票:-2回答:2

当我试图从Dictionary键获取值时,它返回错误

我试过以下方法:

public Dictionary<string, string> Credentials { get; set; }
Approach1: Credentials["Password"]

KeyName是正确的,并出现在我的词典enter image description here

enter image description here它返回错误

+ Credentials [“0”]'Credentials [“0”]'引发了类型'System.Collections.Generic.KeyNotFoundException'string {System.Collections.Generic.KeyNotFoundException}的异常

但是下面的代码按预期工作

Credentials.TryGetValue(Credentials.FirstOrDefault().Key, out string password);

我需要使用字典中的键来获取值,我将收到错误。

c#
2个回答
4
投票

这里的问题只是你使用了错误的密钥。如果您想知道密钥是什么,那么请仔细查看Credentials.FirstOrDefault().Key。如果没有最小的复制品,我无法告诉你它是什么,但就个人而言,我怀疑它是一个尾随的白色空间。

尝试:

var key = Credentials.FirstOrDefault().Key;
Console.WriteLine("'" + key + "'");

这里周围引用的要点是要使额外的空白显而易见。它没有产生明显的答案:你需要查看实际的角色数据(ToCharArray()) - 可能会有unicode恶作剧。

关键不是"0",但这只是被视为可枚举的索引。


1
投票

问题所声称的内容无法再现。这是一个基本特征,任何问题都会在2005年引入Dictionary<>时被注意到。

var Credentials=new Dictionary<string,string>();
Credentials["User"]="2004";
Credentials["Password"]="201900";

Debug.Assert(Credentials["Password"]=="201900");

扔的是这个:

var x=Credentials["0"];

这将正确抛出:

System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.
   at System.ThrowHelper.ThrowKeyNotFoundException()
   at System.Collections.Generic.Dictionary`2.get_Item(TKey key)

因为词典中没有这样的键。

也许有人试图通过索引阅读字典项目?在任何情况下,正确的呼叫将是:

var x=dict.ElementAt(0);

字典的索引器不能用于按索引访问项目。实际上,字典没有任何有意义的顺序。从文档:

出于枚举的目的,字典中的每个项都被视为表示值及其键的KeyValuePair结构。返回项的顺序未定义。

订单可以在项目添加到索引时更改。

© www.soinside.com 2019 - 2024. All rights reserved.