Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Parse Key/Value of a Generic Dictionary in C#

0.00/5 (No votes)
10 Jul 2011 1  
Parse key/value of a Generic dictionary in C#.

Dictionary<key,value> is a useful data structure specially for mapping purposes. After initializing the Dictionary<key,value>, to retrieve the value of a related key, it is necessary to do a lookup of the key, for example, monthPositionMapping["January"]; in the below code.


In this tip, we will see Key or Value parsing of a Generic Dictionary. For example,


C#
Dictionary<string,int> monthPositionMapping = new Dictionary<string,int>()
{
     {"January", 1},
     {"February",2},
     {"March", 3},
};

If we want to query the value of January from monthPositionMapping, then it will find 1 (Key based look-up) and if we query by 1, then it will return January (Value based look-up). It has to be mentioned that a basic rule of Dictionary is, it has to have identical keys, and in addition, I assume all the values also being identical to use the ParseKey and ParseValue methods in this example.


The following code will show how can we query the related value of a key using the key as the search element (for example, January in the above example) and to query the key using the value as the search element (for example, 1 in the above example).


C#
public static class DictionaryParser
{
    public static TKey ParseKey<TKey, TValue>(Dictionary<TKey, TValue> repository, TValue byValue)
    {
        return
            (TKey)repository.Where(keyPair => keyPair.Value.Equals(byValue)).Select(
                  keyPair => keyPair.Key).FirstOrDefault();
    }

    public static TValue ParseValue<TKey, TValue>(Dictionary<TKey, TValue> repository, TKey byKey)
    {
        TValue result;
        return repository.TryGetValue(byKey, out result) ? result : result;
    }
}

In the above code, the ParseKey method will accept a value (byValue) as the search element of the given dictionary (repository) and it will return the related key of value. And the concept for ParseValue is the same but it accepts a key as input.


Here is the usage:


C#
class Program
{
    enum MyKeys
    {
        Key1,
        Key2,
        Key3
    };
    enum PersonalTitles
    {
        Mr,
        Mrs
    }
    enum MainFrameTitles
    {
        M,
        F
    }

    static void Main(string[] args)
    {
        Dictionary<string, string> myDictionary = new Dictionary<string, string>()
        {
            {"Key1", "Value1"},
            {"Key2", "Value2"},
            {"Key3", "Value3"},
        };
        Dictionary<MyKeys, string> myDictionary2 = new Dictionary<MyKeys, string>()
        {
            {MyKeys.Key1, "Value1"},
            {MyKeys.Key2, "Value2"},
            {MyKeys.Key3, "Value3"},
        };
        Dictionary<PersonalTitles, MainFrameTitles> myDictionary3 = 
                         new Dictionary<PersonalTitles, MainFrameTitles>()
        {
            {PersonalTitles.Mr, MainFrameTitles.M},
            {PersonalTitles.Mrs, MainFrameTitles.F},
        };

        var result1 = DictionaryParser.ParseKey<string, string>(myDictionary,"Value221");
        var result2 = DictionaryParser.ParseValue<string, string>(myDictionary,"Key2");
        var result3 = DictionaryParser.ParseKey<MyKeys, string>(myDictionary2,"Value2");
        var result4 = DictionaryParser.ParseValue<MyKeys, string>(myDictionary2,MyKeys.Key2);
        var result5 = DictionaryParser.ParseKey<PersonalTitles, MainFrameTitles>(myDictionary3,MainFrameTitles.M);
    }
}

Also, ParseKey and ParseValue could be use as Extension Methods, for example:


C#
public static class DictionaryExtensions
{
    public static TKey ParseKey<TKey, TValue>(this Dictionary<TKey, TValue> repository, TValue byValue)
    {
        return
            (TKey)repository.Where(keyPair => keyPair.Value.Equals(byValue)).Select(
                  keyPair => keyPair.Key).FirstOrDefault();
    }

    public static TValue ParseValue<TKey, TValue>(this Dictionary<TKey, TValue> repository, TKey byKey)
    {
        TValue result;
        return repository.TryGetValue(byKey, out result) ? result : result;
    }
}

Here is the usage of the above Extension Methods:


C#
var result1 = myDictionary.ParseKey<string, string>("Value221");
var result2 = myDictionary.ParseValue<string, string>("Key2");
var result3 = myDictionary2.ParseKey<MyKeys, string>("Value2");
var result4 = myDictionary2.ParseValue<MyKeys, string>(MyKeys.Key2);
var result5 = myDictionary3.ParseKey<PersonalTitles, MainFrameTitles>(MainFrameTitles.M);

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here