2

i want to create a Dropdownlist with specific numbers in MVC

So in my model i have a property :

public IEnumerable<SelectListItem> Quantities { get; set; }

In my controller i instantiate my model :

Quantities = from s in numbers
             select new SelectListItem { Text = s.ToString()}

numbers is a int array with 10 numbers in it.

This code works but the problem is i cant get the value(index) of the array from 's'.

Does anyone know how i can get this value?

2 Answers 2

3

This is not possible with LINQ expressions. You could use the following:

Quantities = numbers.Select((s, index) => new SelectListItem 
{ 
    Value = index.ToString(), 
    Text = s.ToString()
);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! That works perfectly indeed. I dont realy understand it though, the arguments for .select(Func<int, TResult>selector) for example... Its nice when having working code but more fun if you understand it aswell :)
@wartodust, there are 2 arguments that the anonymous method takes: the first is the current element and the second is an integer representing the index.
Wow. This is a well hidden LINQ feature !
0

You can use the method syntax instead of the query syntax:

var quantities = numbers.Select((x,i) => {...});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.