【问题标题】:Get Object stored in Dictionary using key使用键获取存储在字典中的对象
【发布时间】:2014-10-29 00:07:51
【问题描述】:

我正在使用 Dictionary 对象 (C#) 来存储键(字符串)和值(对象)对。

我可以毫无问题地将对象存储在字典中。但是,访问它们对我不起作用。

这是我想出的代码:

Object con;

if (dict.ContainsKey(theKey))
{
     con = dict.FirstOrDefault(x => x.Value == theKey).Key;
}
else
{
     throw new Exception("Connection instance unavailable : " + theKey);
}

由于某种原因,con 总是返回空。

【问题讨论】:

  • 你为什么不使用Dictionary.TryGetValue()?无论如何, value != key... 你的比较应该是x => x.Key == theKey
  • 我试过x => x.Key == theKey,它只是再次返回密钥。
  • 另外,为什么所有的反对票?我找不到任何与字典中的对象相关的问题。
  • 我也不知道为什么投反对票。

标签: c# dictionary


【解决方案1】:

使用这个:

if (dict.ContainsKey(theKey))
{
     con = dict[theKey];
}

这是 LinqPad 的一个小脚本:

var dictionary = new Dictionary<String, Object>();

dictionary.Add("myKey", new Object());

var myKey = "myKey";
Object con;
if (dictionary.ContainsKey(myKey))
{
    con = dictionary[myKey];
    // con is populated
}

另外,你可以在DotnetFiddle看到这一点

根据 Matthew Watson 的 cmets,使用以下方法比 ContainsKey 更有效:

if (dictionary.TryGetValue(myKey, out con))
{
    // con is populated again
}

此代码进行一次搜索,而 ContainsKey[] 进行两次搜索。

【讨论】:

  • 谢谢!第一部分是我所需要的,它工作正常。从未使用过 LINQPad。
  • @SuperJohn LINQPad 非常适合小试一下。或者我添加了一个指向 DotnetFiddle - 在线服务的链接,类似于 LINQPad。
  • @SuperJohn 请确保您使用上面的TryGetValue() 版本,而不是ContainsKey() 版本。
  • @trailmax TryGetValue() 仅调用私有FindEntry()(返回内部数组中项目的索引)一次,如果找到,则使用它返回值。使用ContainsKey() 后跟数组运算符调用FindEntry() TWICE。因此,后一种方法进行了两次搜索,显然效率较低。 (我认为您一定忽略了 [] 运算符也进行搜索的事实。)
  • @SuperJohn 请参阅上面我对 trailmax 的回复。使用TryGetValue() 只搜索一个字典而不是两个。
【解决方案2】:

你必须使用字典的索引器:

dict.Add("MyKey", new Object());
var result = dict["MyKey"];

【讨论】:

    【解决方案3】:

    我猜您在FirstOrDefault 中的比较是错误的,您正在通过将给定键与Value 进行比较来查找KeyValuePair

    FirstOrDefault(x => x.Value == theKey) // pointless
    

    但是你根本不需要循环字典,你应该使用索引器或TryGetValue。由于您已经检查了密钥是否存在,您可以安全地使用:

    con = dict[theKey];
    

    但是,如果您缺少通过给定键同时为您提供 KeyValuePair 的键和值的方法,您可以使用此扩展方法:

    public static KeyValuePair<TKey, TValue>? TryGetKeyValue<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
    {
        TValue value;
        if (dictionary.TryGetValue(key, out value))
        {
            return new KeyValuePair<TKey, TValue>(key, value);
        }
        return null;
    }
    

    现在您不需要使用FirstOrDefault 循环所有条目来获取它:

    var dict = new Dictionary<string, object>();
    dict.Add("1", "A");
    KeyValuePair<string, object>? pair = dict.TryGetKeyValue("1");
    

    如果未找到密钥pair.HasValue,则返回false

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-11
      • 1970-01-01
      • 2018-08-25
      • 2018-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-16
      相关资源
      最近更新 更多