Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 690
frog_jr Avatar asked Jul 14 '15 18:07

frog_jr


2 Answers

// #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" }
like image 144
Jashaszun Avatar answered Sep 24 '22 18:09

Jashaszun


It sounds like you would benefit from using something like:

Dictionary<string, List<string>> kvlist;

kvlist["qwer"] = new List<string>();
kvlist["qwer"].Add("value1");
kvlist["qwer"].Add("value2");

foreach(var value in kvlist["qwer"]) {
    // do something
}

It would be relatively easy to create a basic mutli-value dictionary class using a Dictionary and List.

This blog post talks more about Microsoft's MultiDictionary type available via NuGet.

like image 30
Robert Horvick Avatar answered Sep 24 '22 18:09

Robert Horvick