Get a text item from an c# SelectList

ⅰ亾dé卋堺 提交于 2020-01-02 01:17:21

问题


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.


回答1:


You can try:

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

Or:

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



回答2:


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

selectList.Items.ToList()[1].Text



回答3:


Try this

selectList.Items.ElementAt(0);

need using System.Linq Namespace




回答4:


Maybe this is what you are looking for?

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


来源:https://stackoverflow.com/questions/17862611/get-a-text-item-from-an-c-sharp-selectlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!