开发者

How to create duplicate rows based on some conditions?

My Dat开发者_如何学Catable has some columns that contains data in the format as 2011~|~2012~|~2013. Now the table has only one row. But based on how many such data is there, that many rows should be created

Hence, in the above format, three rows should be created each having Year column filled as 2011, 2012 and 2013. It doesn't matter that if other columns are being duplicated

Format similar to Year column also exists for some 2-3 more columns such as Sales column states figures as 190~|~250~|~488.

One Important Note: The number of rows here should be 3 (considering year & sales column). It should not be 9 (3 x 3). There is a one-to-one relationship, say in year 2011 sales was 190mn$, for 2012 it was 250 mn$ and for 2013 expected is 488mn$.

The below image explains more in detail.

I guess the funda is cleared. If not, let me know.

Please guide

How to create duplicate rows based on some conditions?


Are you looking for something like this?

private DataTable AlterDataTable(DataTable oldTable)
{
    DataTable newTable = oldTable.Clone();
    foreach (DataRow row in oldTable.Rows)
    {
        var years = row["Year"]
        .ToString()
        .Split(new string[] { "~|~" }, StringSplitOptions.RemoveEmptyEntries)
        .ToList();
        foreach (var year in years)
        {
            row["Year"] = year;
            newTable.ImportRow(row);
        }

    }

    return newTable;
}

Call it as DataTable dataTable = AlterDataTable(dt);

For this requirement, try this

private DataTable AlterDataTable(DataTable oldTable)
{
    DataTable newTable = oldTable.Clone();
    foreach (DataRow row in oldTable.Rows)
    {
        var years = row["Year"]
        .ToString()
        .Split(new string[] { "~|~" }, StringSplitOptions.RemoveEmptyEntries)
        .ToList();
        var sales = row["Sales"]
        .ToString()
        .Split(new string[] { "~|~" }, StringSplitOptions.RemoveEmptyEntries)
        .ToList();
        if (years.Count != sales.Count)
        {
            throw new Exception("Argument count mismatch exception");
        }
        for (var i = 0; i < years.Count; i++)
        {
            row["Year"] = years[i];
            row["Sales"] = sales[i];
            newTable.ImportRow(row);
        }
    }
    return newTable;
}

Please note that the splits should be having the same count.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜