I want to bind a dictionary to DropDownList. But before binding
I want to sort it alphabetically – either by key or value.
How can I obtain that? Is there some kind of build in sort
function or a trick?
Here is my code:
Dim Dic1 As New Dictionary(Of String, String)
Dic1.Add("1", "pear")
Dic1.Add("2", "apple")
Dic1.Add("3", "juice")
Dic1.Add("4", "milk")
Dic1.Add("5", "cornflakes")
drpProduct.DataSource = Dic1
drpProduct.DataTextField = "Value"
drpProduct.DataValueField = "Key"
drpProduct.DataBind()
Thanks in advance,
Best regards.
You can use Linq:
Change
Order By kv.ValuetoOrder By kv.Keyif you want to order by the keys instead.But as Adi has already mentioned, it is better to use a
SortedDictionaryfrom the start then.