在c#中使用foreach和两种类型的条件

时间:2014-03-10 09:20:12

标签: c# foreach

我使用下拉列表进行搜索。文本值应与值不同。所以,我创建了两种方法:

    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应该出现在值字段中。我该如何添加?

4 个答案:

答案 0 :(得分:4)

你可以使用linq并在一个查询中完成它:

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;

答案 1 :(得分:3)

而不是foreach,您可以使用枚举器在同一时间迭代这两个列表

IEnumerator enum1 = lstRoles.GetEnumerator();
IEnumerator enum2 = lstFunctions.GetEnumerator();

int i = 1;
while ((enum1.MoveNext()) && (enum2.MoveNext()))
{
        selectListRoles.Add(new SelectListItem
        {
            Text = enum1.Current,
            Value = enum2.Current,
            Selected = (i == 0)
        });

        i++;
}

答案 2 :(得分:2)

怎么样

var selectListRoles = _repository.GetRolesForFindJobseekers().Zip(
    _repository.GetFunctionsForRolesFindJobSeekers(),
    (role, function) => new SelectListItem
        {
            Text = role,
            Value = function,
            Selected = false
        }).ToList();
selectListRoles[0].Selected = true;
ViewData["RolesForJobSeekers"] = selectListRoles;

如果您不想实例化selectListRoles

// If you know selectListRoles starts empty, use 0 instead of baseIndex.
var baseIndex = selectListRoles.Count;
selectListRoles.AddRange(_repository.GetRolesForFindJobseekers().Zip(
    _repository.GetFunctionsForRolesFindJobSeekers(),
    (role, function) => new SelectListItem
        {
            Text = role,
            Value = function,
            Selected = false
        }));
selectListRoles[baseIndex].Selected = true;

答案 3 :(得分:1)

您可以先将这两个列表合并为一个,然后循环显示该列表。

var lstCombined =
    lstRoles
     .Zip(lstFunctions, (role, function) => new {Role = role, Function = function}).ToList();

int i = 1;

foreach (var item in lstCombined)
{
    selectListRoles.Add(new SelectListItem
                            {
                                Text = item.Role,
                                Value = item.Function,
                                Selected = (i == 0)
                            });

    i++;
}