I used dropdown for search. The text value should different from the value. So, I created 2 types of methods:
List<string> lstRoles = new List<string>();
lstRoles = _repository.GetRolesForFindJobseekers();
List<string> lstFunctions = new List<string>();
lstFunctions = _repository.GetFunctionsForRolesFindJobSeekers();
List<SelectListItem> selectListRoles = new List<SelectListItem>();
int i = 1;
foreach (string role in lstRoles)
{
selectListRoles.Add(new SelectListItem
{
Text = role,
Value = role,
Selected = (i == 0)
});
i++;
}
ViewData["RolesForJobSeekers"] = selectListRoles;
lstFunctions
should come in the value field. How will I add this?
No, a foreach simply works for each element.
As it turned out, FOREACH is faster on arrays than FOR with length chasing. On list structures, FOREACH is slower than FOR. The code looks better when using FOREACH, and modern processors allow using it. However, if you need to highly optimize your codebase, it is better to use FOR.
The working of foreach loops is to do something for every element rather than doing something n times. There is no foreach loop in C, but both C++ and Java have support for foreach type of loop. In C++, it was introduced in C++ 11 and Java in JDK 1.5. 0 The keyword used for foreach loop is “for” in both C++ and Java.
The Foreach loop uses the loop variable instead of the indexed element to perform the iteration.
You could use linq and get it done in one query:
var selectListRoles =
lstRoles
.Zip(lstFunctions, (role, function) => new { role, function })
.Select((rf, i) => new SelectListItem()
{
Text = rf.role,
Value = rf.function,
Selected = (i + 1 == 0),
})
.ToList();
ViewData["RolesForJobSeekers"] = selectListRoles;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With