Best way add a new column with sequential numbering in an existing data table

前端 未结 3 1944
囚心锁ツ
囚心锁ツ 2021-02-11 02:03

I have a non empty datatable . What is the best way to add another column to it that has sequential numbering starting from 1.

I tried the following code. But did not wo

3条回答
  •  北海茫月
    2021-02-11 02:15

    I think you could achieve that by using a 2nd "helper" data table that would contain just an auto-increment field and then you populate/merge it with the existing data, something like this:

    DataTable dtIncremented  = new DataTable(dt.TableName);
    DataColumn dc            = new DataColumn("Col1");
    dc.AutoIncrement         = true;
    dc.AutoIncrementSeed     = 1;
    dc.AutoIncrementStep     = 1;
    dc.DataType              = typeof(Int32);    
    dtIncremented.Columns.Add(dc);
    
    dtIncremented.BeginLoadData();
    
    DataTableReader dtReader = new DataTableReader(dt);
    dtIncremented.Load(dtReader);
    
    dtIncremented.EndLoadData();
    

    And then you would just return dtIncremented table instead of the original dt. Not an elegant solution but should work.

提交回复
热议问题