I am running the following:
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();
Where AnswerType looks like this:
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" },
};
}
}
}
But I am getting an error message saying that “Can’t convert SelectListItem to string”. Is there a way that I can just extract the Text from the SelectListItem?
In your code
AnswerType.SingleOrDefault(s => s.Value == "2")will returnSelectedListIteminstance, not astring.If you need to get text the query would be:
or