Click here to Skip to main content
15,867,453 members
Articles / Programming Languages / C#
Tip/Trick

Parse Key/Value of a Generic Dictionary in C#

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
10 Jul 2011CPOL1 min read 34.5K   3   3
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Australia Australia

Comments and Discussions

 
QuestionGood job Pin
TanNguyen199125-Sep-18 16:35
TanNguyen199125-Sep-18 16:35 
GeneralMy vote of 5 Pin
Davor K.2-Feb-13 2:01
Davor K.2-Feb-13 2:01 
GeneralRe: My vote of 5 Pin
Mohammad A Rahman2-Feb-13 2:10
Mohammad A Rahman2-Feb-13 2:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.