Dada una lista:
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")); }(NOTA: hay varios valores para la clave "qwer" y varias claves para el valor "asdf").
1) ¿Hay una mejor manera de devolver una lista de todas las claves que simplemente hacer un foreach en la lista KeyValuePair?
2) Del mismo modo, ¿hay una mejor manera de devolver una lista de todos los valores para una clave dada que usar un foreach?
3) Y luego, ¿qué tal devolver una lista de claves para un valor dado?
Gracias...
// #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" }Parece que se beneficiaría de usar algo como:
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 }Sería relativamente fácil crear una clase básica de diccionario de valores múltiples utilizando un diccionario y una lista.
Esta publicación de blog habla más sobre el tipo MultiDictionary de Microsoft disponible a través de NuGet.
Puede usar NameValueCollection desde System.Collection.Specialized espacio de nombres:
NameValueCollection KV_List = new NameValueCollection(); KV_List.Add("qwer", "asdf"); KV_List.Add("qwer", "ghjk"); KV_List.Add("zxcv", "asdf"); KV_List.Add("hjkl", "uiop");Ejemplo de uso:
string singleValue = KV_List["zxcv"]; // returns "asdf" string[] values = KV_List.GetValues("qwer"); // returns "asdf, "ghjk" string[] allKeys = KV_List.AllKeys; string[] allValues = KV_List.AllKeys;