Get text element from C # SelectList

Using Visual Studio Express 2012 for Web and Razor, I create a selection 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 think I can do this:

 selectList.Items[1].Text 

But this leads to the message: "Cannot apply indexing with [] to an expression like" System.Collections.IEnumerable "

Thanks.

+6
source share
4 answers

You can try:

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

Or:

 selectList.Where(p => p.Value == "2").First().Text; 
+11
source

You can convert it to a List that will give you access to the index

 selectList.Items.ToList()[1].Text 
+3
source

try it

 selectList.Items.ElementAt(0); 

need using System.Linq Namespace

0
source

Perhaps this is what you are looking for?

 selectList.Items.FindByValue("1").Text 
0
source

Source: https://habr.com/ru/post/950282/


All Articles