Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从列表中的KeyValuePair检索值?_C#_List_Contain_Keyvaluepair - Fatal编程技术网

C# 如何从列表中的KeyValuePair检索值?

C# 如何从列表中的KeyValuePair检索值?,c#,list,contain,keyvaluepair,C#,List,Contain,Keyvaluepair,我有下面的列表,需要对其运行Contains()或类似的方法来检索与特定键关联的值。我该怎么做?我到处都找遍了,试过很多东西,但我似乎没弄明白 List<KeyValuePair<string, int>> shopInventory = new List<KeyValuePair<string, int>>(); List shopInventory=新列表(); 我认为这是一个大致如下的问题: shopInventory.Contains(

我有下面的列表,需要对其运行Contains()或类似的方法来检索与特定键关联的值。我该怎么做?我到处都找遍了,试过很多东西,但我似乎没弄明白

List<KeyValuePair<string, int>> shopInventory = new List<KeyValuePair<string, int>>();
List shopInventory=新列表();
我认为这是一个大致如下的问题:

shopInventory.Contains((KeyValuePair<string, int>
shopInventory.Contains((KeyValuePair
如果我忽略了任何重要信息,我很乐意提供。

您可以使用LINQ

return shopInventory.First(c => c.Key == key).Value;
当然,您可能还需要错误处理

如果你经常使用它,你也可以使用字典。

你可以使用
Where(…)

如果至少存在一对密钥等于
searchKey


如果要对与提供的搜索键匹配的所有对执行某些操作,则可以将
.Count()>0
保留在外,并对表达式的结果执行操作。

为什么要使用KeyValuePair列表?谢谢!我想我尝试过类似的操作,但没有输入“.Value”.现在一切正常。
shopInventory.Where (kvp => kvp.Key == searchKey).Count() > 0