C#Datatable复制Row

想实现的目的

如果Input为4 那改行 就复制四行

有老板可以教一下嘛 效率高一些

回答

internal class Program
{
    static void Main(string[] args)
    {
        var dt = GetTestData();
        ChanageDt(dt);
    }

    private static DataTable GetTestData()
    {
        DataTable dt = new DataTable();

        dt.Columns.Add("input", typeof(int));
        dt.Columns.Add("name", typeof(string));
        dt.Columns.Add("key", typeof(int));

        var row1 = dt.NewRow();
        row1["input"] = 1;
        row1["name"] = "张三";
        row1["key"] = 20;

        var row2 = dt.NewRow();
        row2["input"] = 2;
        row2["name"] = "李四";
        row2["key"] = 25;

        var row3 = dt.NewRow();
        row3["input"] = 3;
        row3["name"] = "王五";
        row3["key"] = 30;
                
        dt.Rows.Add(row1);
        dt.Rows.Add (row2);
        dt.Rows.Add (row3);

        return dt;
    }

    private static void ChanageDt(DataTable dt)
    {
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            var row = dt.Rows[i];
            int input = int.Parse(row["input"].ToString());
            for (int j = 0; j < input - 1; j++)
            {
                var newRow = dt.NewRow();
                newRow["input"] = row["input"];
                newRow["name"] = row["name"];
                newRow["key"] = row["key"];
                dt.Rows.InsertAt(newRow, i + 1);
            }
            i += input - 1;
        }
    }
}
以上是C#Datatable复制Row的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>