使用键将对象存储在Dictionary中

时间:2014-09-04 09:40:36

标签: c# dictionary

我正在使用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始终返回空。

3 个答案:

答案 0 :(得分:2)

使用此:

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

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

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

答案 1 :(得分:1)

你必须使用字典索引器:

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

答案 2 :(得分:1)

我想您在FirstOrDefault中的比较是错误的,您正在寻找一个给定密钥的KeyValuePair,并将其与此处的Value进行比较:

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

相关问题