Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a text item from an c# SelectList

Using Visual Studio Express 2012 for Web and Razor, I create a select list:

List<SelectListItem> list = new List<SelectListItem>();
list.Add(new SelectListItem { Text = "Yes", Value = "1" });
list.Add(new SelectListItem { Text = "No", Value =  "2" });

SelectList selectList = new SelectList(list, "Value", "Text", null);

Later, I want to get the text associated with a specific element in selectList. As a newbie, I'd think I could do this:

selectList.Items[1].Text

But that results in the message, "Cannot apply indexing with [] to an expression of type 'System.Collections.IEnumerable'"

Thanks.

like image 800
Steve A Avatar asked Jul 25 '13 15:07

Steve A


1 Answers

You can try:

selectList.Skip(1).First().Text;

Or:

selectList.Where(p => p.Value == "2").First().Text;
like image 89
Francisco Avatar answered Sep 20 '22 22:09

Francisco