选择KeyValuePair列表的值

如何根据检查键值从keyvaluepair列表中选择值

List<KeyValuePair<int, List> myList = new List<KeyValuePair<int, List>(); 

在这里,我想得到

 list myList[2].Value when myLisy[2].Key=5. 

我怎样才能做到这一点?

如果你还是需要使用List我会在这个查询中使用LINQ :

 var matches = from val in myList where val.Key == 5 select val.Value; foreach (var match in matches) { foreach (Property prop in match) { // do stuff } } 

您可能想要检查匹配为null。

如果您坚持使用List,则可以使用

 myList.First(kvp => kvp.Key == 5).Value 

或者,如果您想使用字典(可能比其他答案中所述的列表更适合您的需要),您可以轻松地将列表转换为字典:

 var dictionary = myList.ToDictionary(kvp => kvp.Key); var value = dictionary[5].Value; 

使用Dictionary> 。 那你可以做

 List list = dict[5]; 

如:

 Dictionary> dict = new Dictionary>(); dict[0] = ...; dict[1] = ...; dict[5] = ...; List item5 = dict[5]; // This works if dict contains a key 5. List item6 = null; // You might want to check whether the key is actually in the dictionary. Otherwise // you might get an exception if (dict.ContainsKey(6)) item6 = dict[6]; 

注意

.NET 2.0中引入的通用Dictionary类使用KeyValuePair。

你可以更好地利用它

 Dictionary.ICollection> 

并使用ContainsKey Method检查密钥是否存在..

示例:

 ICollection> openWith = new Dictionary(); openWith.Add(new KeyValuePair("txt", "notepad.exe")); openWith.Add(new KeyValuePair("bmp", "paint.exe")); openWith.Add(new KeyValuePair("dib", "paint.exe")); openWith.Add(new KeyValuePair("rtf", "wordpad.exe")); if (!openWith.ContainsKey("txt")) { Console.WriteLine("Contains Given key"); } 

编辑

为了获得价值

 string value = ""; if (openWith.TryGetValue("tif", out value)) { Console.WriteLine("For key = \"tif\", value = {0}.", value); //in you case //var list= dict.Values.ToList(); } 

在你的情况下它会

 var list= dict.Values.ToList();