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.
You can try:
selectList.Skip(1).First().Text;
Or:
selectList.Where(p => p.Value == "2").First().Text;
您可以将其转换为List
,以便您访问索引器
selectList.Items.ToList()[1].Text
Try this
selectList.Items.ElementAt(0);
need using System.Linq
Namespace
也许这就是你要找的?
selectList.Items.FindByValue("1").Text
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.