简体   繁体   中英

How C# SortedList get key by value?

There is a SortedList

slLanguage = new SortedList();
slLanguage.Add("Bahasa","id-ID");
slLanguage.Add("Chinese Simplified(中文简体)","zh-CN");
slLanguage.Add("Chinese Traditional(中文繁體)","zh-TW");      
slLanguage.Add("Kazakh","kk-KZ");
slLanguage.Add("Russian(русский)","ru-RU");
slLanguage.Add("Vietnamese(Việt)","vi-VN");
slLanguage.Add("English", "en-US");

How can I get the key by value?

For example: Get the item key "zh-CN"

If you would like to get the key from a value, you may use SortedList.IndexOfValue(object value) to get the index of the value you specify. Then, use SortedList.GetKey(int index) to return a key as object from the value's index we just gathered.

Example

SortedList slLanguage = new SortedList(); //Initializes a new SortedList of name slLanguage
//Add the keys and their values to the list
slLanguage.Add("Bahasa", "id-ID");
slLanguage.Add("Chinese Simplified(中文简体)", "zh-CN");
slLanguage.Add("Chinese Traditional(中文繁體)", "zh-TW");
slLanguage.Add("Kazakh", "kk-KZ");
slLanguage.Add("Russian(русский)", "ru-RU");
slLanguage.Add("Vietnamese(Việt)", "vi-VN");
slLanguage.Add("English", "en-US");
//
object returnedKey = slLanguage.GetKey(slLanguage.IndexOfValue("zh-CN")); //Gets the key from zh-CN as returnedKey of type object

Thanks,
I hope you find this helpful :)

There's probably a better way to do this, but here's one way to do it:

int index = slLanguage.IndexOfValue("zh-CN");
var item = slLanguage.GetKey(index);

Looking the key from Value would be not efficient and defeats the purpose of sorted List. Sorted list is really a sorted Dictionary named confusingly as SortedList.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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