在for-each循环中创建多个行

时间:2014-11-10 18:09:39

标签: c# ado.net

使用旧应用程序时,我看到此代码:,它正在使用DataTableDataRow内容。

foreach (string networkIdToCreate in networkIdsToCreate)
{
    HTExtractSchema.HTProviderMedicalGroupContractRow rHTProviderMedicalGroupContract = tblHTProviderMedicalGroupContract.NewHTProviderMedicalGroupContractRow();
    rHTProviderMedicalGroupContract.ItemArray = rHTProviderMedicalGroupContractDefaults.ItemArray;
    rHTProviderMedicalGroupContract.NetworkId = networkIdToCreate;
    rHTProviderMedicalGroupContract.Business = "470";
    tblHTProviderMedicalGroupContract.Rows.Add(rHTProviderMedicalGroupContract);
}

因此,它会创建新行,在其中放入一些值并将其添加到DataTable

现在我想修改它以创建两行而不是一行,所有值都相同,除了" Business"字段,它是上面代码中最后一行之前的一行。

所以我这样做了:

foreach (string networkIdToCreate in networkIdsToCreate)
{
    HTExtractSchema.HTProviderMedicalGroupContractRow rHTProviderMedicalGroupContract = tblHTProviderMedicalGroupContract.NewHTProviderMedicalGroupContractRow();
    rHTProviderMedicalGroupContract.ItemArray = rHTProviderMedicalGroupContractDefaults.ItemArray;
    rHTProviderMedicalGroupContract.NetworkId = networkIdToCreate;
    rHTProviderMedicalGroupContract.Business = "470";
    tblHTProviderMedicalGroupContract.Rows.Add(rHTProviderMedicalGroupContract);

    HTExtractSchema.HTProviderMedicalGroupContractRow rHTProviderMedicalGroupContract2 = tblHTProviderMedicalGroupContract.NewHTProviderMedicalGroupContractRow();
    rHTProviderMedicalGroupContract2.ItemArray = rHTProviderMedicalGroupContractDefaults.ItemArray;
    rHTProviderMedicalGroupContract2.NetworkId = networkIdToCreate;
    rHTProviderMedicalGroupContract2.Business = "475";
    tblHTProviderMedicalGroupContract.Rows.Add(rHTProviderMedicalGroupContract2);
}

但是我想知道除了这个复制粘贴之外还有更好的方法吗?所以,如果有人看到代码赢了,不要嘲笑我:D

1 个答案:

答案 0 :(得分:1)

只需添加此内部循环

foreach(var business in new[] {"470", "475"})
{
    ...
    rHTProviderMedicalGroupContract.Business = business ;
    ...
}

修改

或者您可以使用方法

private void CreatRow(
    string networkIdToCreate,
    string business)
{
    HTExtractSchema.HTProviderMedicalGroupContractRow rHTProviderMedicalGroupContract = 
        tblHTProviderMedicalGroupContract.NewHTProviderMedicalGroupContractRow();
    rHTProviderMedicalGroupContract.ItemArray = 
        rHTProviderMedicalGroupContractDefaults.ItemArray;
    rHTProviderMedicalGroupContract.NetworkId = networkIdToCreate;
    rHTProviderMedicalGroupContract.Business = business;
    tblHTProviderMedicalGroupContract.Rows.Add(rHTProviderMedicalGroupContract);
}

并像这样使用

foreach (string networkIdToCreate in networkIdsToCreate)
{
    CreatRow(networkIdToCreate, "470");
    CreatRow(networkIdToCreate, "475");
    if(networkIdToCreate == "2" || networkIdToCreate == "6")
    {
        CreateRow(networkIdToCreate, "474");
    }
}

请注意,您可能需要传入tblHTProviderMedicalGroupContract,具体取决于其范围