26

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

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

在这里我想得到

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

我怎样才能做到这一点?

4

4 回答 4

23

如果您仍然需要使用列表,我会使用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
    }
}

您可能想要检查匹配是否为空。

于 2012-07-09T07:55:49.140 回答
13

如果你被列表卡住了,你可以使用

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

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

var dictionary = myList.ToDictionary(kvp => kvp.Key);
var value = dictionary[5].Value;
于 2012-07-09T07:24:47.687 回答
3

使用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];
于 2012-07-09T07:20:55.273 回答
0

笔记

.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>(); 
于 2012-07-09T07:23:28.930 回答