Dictionary Search

7

I have the following dictionary:

public static Dictionary<string, string> ObterCodigo()
{
    return new Dictionary<string, string>
       {
           {"18", "Teste"},     
           {"19", "Teste"},
           {"02", "AAA"},
           {"03", "AAA"},
           {"109", "BBB"},
           {"157", "BBB"},
       };
}

I would like my combobox to search only for "AAA" values. Can you do it?

    
asked by anonymous 29.01.2014 / 14:12

2 answers

9

If I understand you, you just want to return the Keys whose value is "AAA". I would do this with LINQ, available from .NET 3.5 (if you could specify which one you use would be better).

var valores = from item in ObterCodigo()
              where item.Value == "AAA"
              select item.Key;

This returns only the keys. If you want to return KeyValuePair<string, string> , just select item instead of item.Key .

Another way, also with LINQ, is:

var valores = ObterCodigo()
              .Where(item => item.Value == "AAA")
              .Select(item => item.Key);

Note that this returns an instance of IEnumerable<string> . Depending on which ComboBox implementation you are using, you will need to enumerate it first. To do this, simply use the ToList() function in the return.

Bonus: If you can not use LINQ (either because you are using an old version of the Framework or because your boss does not let me - it has happened to me - it follows a version without it - well similar to what it would look like in Java):

Dictionary<string, string> codigos = new Dictionary<string, string>();
foreach (KeyValuePair item in ObterCodigo())
    if (item.Value == "AAA")
        codigos.Add(item.Key, item.Value);
    
29.01.2014 / 14:16
0

You can build a separate dictionary for just that.

You can populate it as follows:

Dictionary<string, string> newDic = new Dictionary<string, string>();
Dictionary<string, string> oldDic = ObterCodigo();
foreach (string key in oldDic.Keys)
{
    if (oldDic[key] == "AAA") newDic.add(key, oldDic[key]);
}

At the end of the section above, the newDic dictionary will only contain the desired items.

    
29.01.2014 / 14:17