使用键获取存储在字典中的对象 [英] Get Object stored in Dictionary using key

查看:71
本文介绍了使用键获取存储在字典中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using a Dictionary object (C#) to store key (string) and value (Object) pairs.

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

I am able to store the Objects in the dictionary without a problem. However, accessing them is not working for me.

这是我想出的代码:

Object con;

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

由于某些原因,con始终返回空.

For some reason, con always returns empty.

推荐答案

使用此:

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

这是LinqPad的小脚本:

Here is a little script for 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的评论,使用以下方法比ContainsKey更有效:

As per comments from Matthew Watson, using the following method is more efficient than ContainsKey:

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

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

This code conducts search once, where as ContainsKey and [] does search twice.

这篇关于使用键获取存储在字典中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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