从 c# SelectList 获取文本项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17862611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:40:44  来源:igfitidea点击:

Get a text item from an c# SelectList

c#asp.net-mvcrazor

提问by Steve A

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

使用 Visual Studio Express 2012 for Web 和 Razor,我创建了一个选择列表:

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 中的特定元素关联的文本。作为新手,我认为我可以这样做:

selectList.Items[1].Text

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

但这会导致消息“无法将 [] 索引应用于‘System.Collections.IEnumerable’类型的表达式”

Thanks.

谢谢。

采纳答案by Francisco

You can try:

你可以试试:

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

Or:

或者:

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

回答by James

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

您可以将其转换为 a List,这将使您可以访问索引器

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

回答by James

Try this

尝试这个

selectList.Items.ElementAt(0);

need using System.LinqNamespace

需要using System.Linq命名空间

回答by Funtastic

Maybe this is what you are looking for?

也许这就是你要找的?

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