选择键值对列表的值

28

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

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

这里我想要获取

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

我该如何实现这个?


3
你为什么需要一个 List<KeyValuePair<int, ...>> 而不是一个简单的 Dictionary<int, ...> 呢? - Joey
键包含重复的值。因此,在这里使用了KeyValuePair而不是Dictionary。 - Devi
太好了!如果您将帮助您的答案标记为“已接受”,那就更好了。 - Thorsten Dittmar
4个回答

24

如果您仍需要使用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。


如果您正在查找基于键的特定KeyValuePair,可以执行以下操作:var kvpValue = (from kvp in kvpList where kvp.Key == key select kvp.Value).FirstOrDefault(); - Jourdan

16

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

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

或者,如果你想使用字典(这可能比其他回答中提到的列表更适合你的需求),你可以轻松地将列表转换为字典:

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

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

1
这是一个好主意,但你必须确保在你的集合中没有重复的键(int值)。你可以将重复的键存储在列表中,但不能存储在字典中。 - Marek Dzikiewicz
是的,这也是我理解 OP 想要的:在这里,当 myLisy[2].Key=5 时,我想要获取 myList[2].Value 列表。如果有多个键的值为 5,他会选择哪一个? - Thorsten Dittmar

1

注意

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

谢谢。从这里我们可以检查keyvaluepair的键。但是List<KeyValuePair<int,List<Properties>>包含属性列表。我如何根据索引和keyvaluepair的键获取该属性?我如何同时检查这两个条件? - Devi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接