无法从列表<键值对>中检索数据

本文关键字:检索 数据 键值对 列表 | 更新日期: 2023-09-27 18:25:16

List<KeyValuePair<String, String> myList = new List<KeyValuePair<String, String>>();
myList.Add(new KeyValuePair<String, SelectList>("theKey", "FIND THIS!"));

如何从只知道theKey myList中检索"FIND THIS!"?此尝试不起作用。

String find = myList.Where(m => m.Key == "theKey");

来自其他语言,我一直有可能在大型关联数组中搜索并检索如下值:array[key] = value;

如何在 C# 中执行此操作?

无法从列表<键值对>中检索数据

而不是 List<KeyValuePair> ,使用 Dictionary<string, SelectList>,然后您可以像 :

array[key] = value;

你可以像这样使用字典:

Dictionary<String, SelectList> dictionary= new Dictionary<String, SelectList>();
dictionary.Add("theKey", "FIND THIS!");
Console.WriteLine(dictionary["theKey"]);

您可能正在寻找Dictionary<TKey, TValue>

Dictionary<string, string> myDict = new Dictionary<string, string>();
myDict.Add("theKey", "FIND THIS!");

现在您可以通过键找到值:

string value = myDict["theKey"];

您可以通过以下方式更改值:

myDict["theKey"] = "new value";  // works even if the key doesn't exist, then it will be added

请注意,键必须是唯一的。

字典怎么样?

IDictionary<String, String> foo = new Dictionary<String, String>();
foo.Add("hello","world");

现在您可以使用 []

foo["Hello"];

但是使用 C#

string value;
if(foo.TryGetValue("Hello" , out value)){
   // now you have value
}

更可取,更安全。

如其他答案中所述,您应该为此使用字典。

但是,您的线路String find = myList.Where(m => m.Key == "theKey");不起作用的原因是myList.Where(m => m.Key == "theKey");将返回KeyValuePair。如果您只想要值,您可以尝试:

String find = myList.Where(m => m.Key == "theKey").Single().Value;

或者,如果您需要检查空值,那么也许:

var findKeyValue = myList.Where(m => m.Key == "theKey").SingleOrDefault();
if(findKeyValue != null)
{
    var find = findKeyValue.Value;
}

您还可以使用以下代码片段(在这种情况下,您将具有值或 null(

var find = myList.Where(m => m.Key == "theKey").Select(kvp => kvp.Value).SingleOrDefault();