简体   繁体   English

无法从列表中检索数据<keyvaluepair>

[英]Can't retrieve data from list<keyvaluepair>

List<KeyValuePair<String, String> myList = new List<KeyValuePair<String, String>>();

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

How can I retrieve "FIND THIS!" 我怎样才能找到"FIND THIS!"找到"FIND THIS!" from myList knowing only theKey ? myList只知道theKey This attempt is not working. 这种尝试无效。

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

Coming from other languages, I've always had the possibility to search in big associative arrays and retrieve values like this: array[key] = value; 来自其他语言,我总是有可能搜索大关联数组并检索这样的值: array[key] = value;

How can I do this in C#? 我怎么能在C#中做到这一点?

Instead of List<KeyValuePair> , use Dictionary<string, SelectList> and then you can access it like : 而不是List<KeyValuePair> ,使用Dictionary<string, SelectList> ,然后你可以访问它,如:

array[key] = value;

You can use Dictionary like: 你可以像使用字典一样:

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

Console.WriteLine(dictionary["theKey"]);

You are probably looking for the Dictionary<TKey, TValue> : 您可能正在寻找Dictionary<TKey, TValue>

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

now you can find the value via the key: 现在你可以通过键找到值:

string value = myDict["theKey"];

You can change the value in this way: 您可以通过以下方式更改值:

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

Note that the keys must be unique. 请注意,键必须是唯一的。

How about Dictionary ? 字典怎么样?

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

now you can use [] 现在你可以用[]

foo["Hello"];

however with C# 但是用C#

string value;

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

is much more preferable and safer. 更加优选和安全。

As mentioned in other answers you should use a Dictionary for this. 如其他答案中所述,您应该使用字典。

However, the reason your line String find = myList.Where(m => m.Key == "theKey"); 但是,你的行String find = myList.Where(m => m.Key == "theKey"); is not working is that myList.Where(m => m.Key == "theKey"); 不工作的是myList.Where(m => m.Key == "theKey"); will return a KeyValuePair . 将返回KeyValuePair If you just want the value you could try: 如果您只想要价值,可以尝试:

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

or if you need to check for nulls then maybe: 或者如果你需要检查空值,那么可能:

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

You can also use the following snippet (in which case you'll either have the value or null) 您还可以使用以下代码段(在这种情况下,您将拥有值或null)

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

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

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