Search code examples
c#listkeyvaluepair

C# get keys and values from List<KeyValuePair<string, string>


Given a list:

    private List<KeyValuePair<string, string>> KV_List = new List<KeyValuePair<string, string>>();
    void initList()
    {
        KV_List.Add(new KeyValuePair<string, string>("qwer", "asdf"));
        KV_List.Add(new KeyValuePair<string, string>("qwer", "ghjk"));
        KV_List.Add(new KeyValuePair<string, string>("zxcv", "asdf"));
        KV_List.Add(new KeyValuePair<string, string>("hjkl", "uiop"));
    }

(NOTE: there are multiple values for the key "qwer" and multiple keys for the value "asdf".)

1) Is there a better way to return a list of all keys than just doing a foreach on the KeyValuePair List?

2) Similarly, is there a better way to return a list of all values for a given key than using a foreach?

3) And then, how about returning a list of keys for a given value?

Thanks...


Solution

  • // #1: get all keys (remove Distinct() if you don't want it)
    List<string> allKeys = (from kvp in KV_List select kvp.Key).Distinct().ToList();
    // allKeys = { "qwer", "zxcv", "hjkl" }
    
    // #2: get values for a key
    string key = "qwer";
    List<string> values = (from kvp in KV_List where kvp.Key == key select kvp.Value).ToList();
    // values = { "asdf", "ghjk" }
    
    // #3: get keys for a value
    string value = "asdf";
    List<string> keys = (from kvp in KV_List where kvp.Value == value select kvp.Key).ToList();
    // keys = { "qwer", "zxcv" }