Click here to Skip to main content
Click here to Skip to main content

Parse Key/Value of a Generic Dictionary in C#

, 10 Jul 2011
Rate this:
Please Sign up or sign in to vote.
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,

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).

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:

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:

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:

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)

About the Author

Mohammad A Rahman
Software Developer
Australia Australia
Designer and Architect.
Author of the Expert C# 5.0: with the .NET 4.5 Framework book

Comments and Discussions

 
GeneralMy vote of 5 PinmemberDavor K.2-Feb-13 2:01 
GeneralRe: My vote of 5 PinmemberMohammad A Rahman2-Feb-13 2:10 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140721.1 | Last Updated 10 Jul 2011
Article Copyright 2011 by Mohammad A Rahman
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid