Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert ListItemCollection (dropdownlist.items) to a dictionary<string,string>?

How to convert ListItemCollection (DropDownList.items) to a Dictionary<String, String>(I know it can be done through for each loop) is there any other way linq?

like image 225
Grasshopper Avatar asked Jul 05 '11 17:07

Grasshopper


2 Answers

You can use LINQ:

collection.Cast<ListItem>().ToDictionary(i => i.Value, i => i.Text);

It's not immediately known what the type of the item is, hence the cast method (at least intellisense didn't bring it up for me). But ToDictionary() should get you there, and specify whatever you want as the key and the value.

HTH.

like image 125
Brian Mains Avatar answered Oct 13 '22 10:10

Brian Mains


See this question:

var result = 
  dropdownlist.items.Cast<ListItem>()
                   .ToDictionary(item => item.Value, 
                                 item => item.Text, 
                                 StringComparer.OrdinalIgnoreCase);
like image 25
VMAtm Avatar answered Oct 13 '22 09:10

VMAtm