Set all values in SelectList in C#

2019-09-15 01:39发布

问题:

In a SelectList object, I want that the Text property of each element of the SelectList should also be the value. For eg:

SelectList s=new SelectList(some list);
s.ElementAt(i).Value=s.ElementAt(i).Text;

Is there any way to do this APART from using a loop? Is there any inbuilt method or something like that to accomplish this?

回答1:

You can use the following Constructor overload for SelectList:

public SelectList(
    IEnumerable items,
    string dataValueField,
    string dataTextField
)

You can then, provided same list member for dataValueField and dataTextField.



回答2:

If you really want to do it without a loop, just use linq foreach (which is a loop in the background):

s.ToList().ForEach(c=>c.Text = c.Value)


标签: c# selectlist