使用foreach将两个字符串数组值保存到单个表中

时间:2014-06-26 07:35:17

标签: c# arrays foreach

在我看来,我有两种类型的值,我传递给字符串数组。我无法连接两者。我正在使用多选复选框 ..

我的代码:

    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声明中,我正在检查函数数组,然后它会进入。然后我检查角色数组的第二个 foreach 语句。如果角色数组具有计数意味着它将使用roleId进行保存。但是如果我选择单一功能,这个条件就会很好用。如果我选择 2以及更多功能循环将再次进入顶部并再次进入 pref.roles 。它没有检查已经保存的那些角色。它再次增加。实际上会做些什么呢?

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。通过在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)

                    };

         }