我正在运行以下内容:
var abc = new adminModel();
string text = abc.AnswerType.SingleOrDefault(s => s.Value == "2");
string text0 = abc.AnswerType.Single(s => s.Value == "2").Text;
var text1 = (from a in abc.AnswerType
here a.Value == "2"
select a.Text).SingleOrDefault();
AnswerType如下所示:
public class adminModel
{
public IEnumerable<SelectListItem> AnswerType
{
get
{
return new[]
{
new SelectListItem { Value = "1", Text = "1 answer" },
new SelectListItem { Value = "2", Text = "2 answers" },
new SelectListItem { Value = "3", Text = "3 answers" },
new SelectListItem { Value = "4", Text = "4 answers" },
new SelectListItem { Value = "5", Text = "5 answers" },
new SelectListItem { Value = "6", Text = "6 answers" },
new SelectListItem { Value = "7", Text = "7 answers" },
};
}
}
}
但我收到一条错误消息,指出“无法将SelectListItem转换为字符串”。有没有办法可以从SelectListItem中提取文本?
答案 0 :(得分:2)
在您的代码中AnswerType.SingleOrDefault(s => s.Value == "2")
将返回SelectedListItem
个实例,而不是string
。
如果你需要获取文本,查询将是:
string text = AnswerType.Single(s => s.Value == "2").Text;
或
string text = AnswerType
.Where(s => s.Value == "2")
.Select(arg => arg.Text)
.SingleOrDefault();
答案 1 :(得分:1)
试试这个:
string text = AnswerType
.Where(s => s.Value == "2")
.Select(s=> s.Text)
.SingleOrDefault();