Get a text item from an c# SelectList

2019-04-24 11:24发布

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.

4条回答
劳资没心,怎么记你
2楼-- · 2019-04-24 11:39

Maybe this is what you are looking for?

selectList.Items.FindByValue("1").Text
查看更多
干净又极端
3楼-- · 2019-04-24 11:45

Try this

selectList.Items.ElementAt(0);

need using System.Linq Namespace

查看更多
成全新的幸福
4楼-- · 2019-04-24 11:48

You can try:

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

Or:

selectList.Where(p => p.Value == "2").First().Text;
查看更多
戒情不戒烟
5楼-- · 2019-04-24 11:51

You could convert it to a List which would give you access to an indexer

selectList.Items.ToList()[1].Text
查看更多
登录 后发表回答