繁体   English   中英

选择KeyValuePair列表的值

[英]Select Value of List of KeyValuePair

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

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。

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

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];

注意

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

你可以更好地利用它

Dictionary<TKey, TValue>.ICollection<KeyValuePair<TKey, TValue>>

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

示例:

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>(); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM