I have a SelectList that looks like. . .
new SelectList(new[]
{
new { Value = "1", Text = "AK" },
new { Value = "2", Text = "AL" },
new { Value = "3", Text = "AR" },
new { Value = "4", Text = "AZ" },
etc. . .
Given an int I need to be able to select the corresponding Value so I can return the associated Text. So if I have the int 3, I want to ultimately return the string “AR” — how do I do this?
I don’t seem to understand how SelectLists work, I’ve been trying something like:
var stringValue = mySelectList.Where(m => m.Value == myInt).Text;
— This does not work for a couple of reasons:
- .Text is not something I can put at the end of the request as it cannot be resolved
m.Value - myInttells meI cannot convert the source type 'int' to target type 'string', and if I change the int to a string I get the error:cannot convert expression type 'string' to return type 'bool'.
I feel like I am overcomplicating something here. Where did I go wrong?
You probably need something like this:
Wheremethod does not return a SelectListItem, it returns a query. You need to force the query to execute, and get the first result, by using theFirst()method.=(assigning a value) instead of==(comparing two values).