如何根据键值检查从键值对列表中选择值
List<KeyValuePair<int, List<Properties>> myList = new List<KeyValuePair<int, List<Properties>>();
这里我想要获取
list myList[2].Value when myLisy[2].Key=5.
我该如何实现这个?
如何根据键值检查从键值对列表中选择值
List<KeyValuePair<int, List<Properties>> myList = new List<KeyValuePair<int, List<Properties>>();
这里我想要获取
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。
var kvpValue = (from kvp in kvpList where kvp.Key == key select kvp.Value).FirstOrDefault();
- Jourdan如果你被列表困住了,你可以使用
myList.First(kvp => kvp.Key == 5).Value
或者,如果你想使用字典(这可能比其他回答中提到的列表更适合你的需求),你可以轻松地将列表转换为字典:
var dictionary = myList.ToDictionary(kvp => kvp.Key);
var value = dictionary[5].Value;
Dictionary<int, List<Properties>>
。然后你可以这样做:List<Properties> list = dict[5];
如下:
Dictionary<int, List<Properties>> dict = new Dictionary<int, List<Properties>>();
dict[0] = ...;
dict[1] = ...;
dict[5] = ...;
List<Properties> item5 = dict[5]; // This works if dict contains a key 5.
List<Properties> 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];
int
值)。你可以将重复的键存储在列表中,但不能存储在字典中。 - Marek Dzikiewicz注意
.NET 2.0中引入的通用Dictionary类使用KeyValuePair。
最好使用它。
Dictionary<TKey, TValue>.ICollection<KeyValuePair<TKey, TValue>>
使用 ContainsKey 方法
检查键是否存在。
示例:
ICollection<KeyValuePair<String, String>> openWith =
new Dictionary<String, String>();
openWith.Add(new KeyValuePair<String,String>("txt", "notepad.exe"));
openWith.Add(new KeyValuePair<String,String>("bmp", "paint.exe"));
openWith.Add(new KeyValuePair<String,String>("dib", "paint.exe"));
openWith.Add(new KeyValuePair<String,String>("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<Property>();
}
在你的情况下,它将是
var list= dict.Values.ToList<Property>();
List<KeyValuePair<int, ...>>
而不是一个简单的Dictionary<int, ...>
呢? - Joey