Set all values in SelectList in C#

本秂侑毒 提交于 2019-12-11 20:11:31

问题


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)


来源:https://stackoverflow.com/questions/11202654/set-all-values-in-selectlist-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!