[英]Most efficient way in adding identity column to a datatable with data in C#
我有一個數據表
Domain Username
x joe1
y sam1
添加標識列的最有效方法是什么
輸出:
Row Domain Username
2 x joe1
3 y sam1
我希望種子從2開始。
目前這是我的代碼,我使用excel中的值填充了數據表,然后添加了一個標識列。 問題是當我這樣做時,標識列可以理解為空。
reader = ExcelReaderFactory.CreateOpenXmlReader(file.InputStream);
reader.IsFirstRowAsColumnNames = true;
dtDetails = reader.AsDataSet().Tables[0];
DataColumn dc = new DataColumn("Row");
dc.AutoIncrement = true;
dc.AutoIncrementSeed = 2;
dc.AutoIncrementStep = 1;
dtDetails.Columns.Add(dc);
dc.SetOrdinal(0);
我已經解決了問題,但是我不確定這是否是最有效的方法,因為該應用程序將處理成百上千的記錄。
這就是我的方法。
DataTable dtIdentity = new DataTable();
reader = ExcelReaderFactory.CreateOpenXmlReader(file.InputStream);
reader.IsFirstRowAsColumnNames = true;
dtDetails = reader.AsDataSet().Tables[0];
DataColumn columnIdentity = new DataColumn("Row");
columnIdentity.AutoIncrement = true;
columnIdentity.AutoIncrementSeed = 2;
columnIdentity.AutoIncrementStep = 1;
dtIdentity.Columns.Add(columnIdentity);
dtIdentity.Columns.AddRange(new DataColumn[] { new DataColumn("Domain"), new DataColumn("Username") });
foreach (DataRow dr in dtDetails.Rows)
{
dtIdentity.Rows.Add(null, dr[0], dr[1]);
}
我創建了一個新的數據表,並添加了行rolumn(identity)和其他列。 然后,我將數據遍歷數據表並添加每一行。
一個更有效的答案將不勝感激。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.