【问题标题】:Save two string array values into single table using foreach使用 foreach 将两个字符串数组值保存到单个表中
【发布时间】:2014-06-30 15:39:15
【问题描述】:

在我看来,我有两种类型的值,我正在传递给字符串数组。我不能同时连接两者。我正在使用多选 checkbox..

我的代码:

    string[] func= { };
    string[] role= { };

if (!string.IsNullOrEmpty(collection["Area"]))
    func = collection["Area"].Split(',');

if (!string.IsNullOrEmpty(collection["Role"]))
    roles= collection["Role"].Split(',');

foreach (string pf in func )
{
    if (!string.IsNullOrEmpty(collection["role_" + func]))
        role= collection["role_" + func].Split(',');

    if (role!= null && role.Length > 0)
    {
        foreach (string rl in role)
        {
            prefunccpf = new prefunc();
            cpf.CID= cid;
            cpf.FID= Convert.ToInt32(func);
            cpf.RID= Convert.ToInt32(rl);

        }
    }

}

在第一个 foreach 语句中,我正在检查 functions 数组,然后它将进入。然后第二个 foreach 语句我正在检查 roles 数组。如果 roles 数组 有 count 意味着它将与 roleId 一起保存。但是,如果我选择 single function,这种情况会很好地工作。如果我选择 2 和更多功能循环 会再次进入顶部并再次来到 pref.roles。它没有检查这些角色是否已保存。它再次增加。究竟该怎么做呢?

【问题讨论】:

标签: c# arrays foreach


【解决方案1】:

我找到了解决方案。通过在 C# 中使用 Zip 函数,我得到了确切的结果。

我的代码在这里

        string[] func= { };
        string[] rol= { };


        if (!string.IsNullOrEmpty(collection["Area"]))
            func= collection["Area"].Split(',');

        if (!string.IsNullOrEmpty(collection["Role"]))
            roles= collection["Role"].Split(',');

        var lstCombined = roles.Zip(func, (role, func) => new { Role = role, Function = func }).ToList();

       foreach (var pf in lstCombined)
        {     
                    var cpf= new prefunc
                    {
                        CID= candidateId,
                        FID= Convert.ToInt32(pf .Function),
                        RID= Convert.ToInt32(pf .Role)

                    };

         }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多