Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How C# SortedList get key by value?

Tags:

c#

sortedlist

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"

like image 949
user1890688 Avatar asked Dec 10 '12 04:12

user1890688


2 Answers

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 :)

like image 129
Picrofo Software Avatar answered Oct 20 '22 02:10

Picrofo Software


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);
like image 26
xbonez Avatar answered Oct 20 '22 02:10

xbonez