Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using foreach with two types of conditions in c#

Tags:

c#

foreach

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?

like image 510
PoliDev Avatar asked Mar 10 '14 09:03

PoliDev


People also ask

Can we put condition in foreach?

No, a foreach simply works for each element.

Is for faster than foreach?

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.

Is there a for each loop in C?

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.

What type of variable would you create to use in a foreach loop?

The Foreach loop uses the loop variable instead of the indexed element to perform the iteration.


1 Answers

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;
like image 168
Enigmativity Avatar answered Oct 06 '22 01:10

Enigmativity