在c#中对两种条件使用foreach

本文关键字:foreach 条件 两种 | 更新日期: 2023-09-27 17:49:18

我使用下拉菜单进行搜索。文本值应该与值不同。因此,我创建了两种方法:

    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应该出现在value字段中。我怎么加这个?

在c#中对两种条件使用foreach

您可以使用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;

可以使用枚举数同时遍历两个列表,而不是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++;
}

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

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++;
}

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;