【C#】在datatable中添加一序号列,编号从1依次递增,并且在第一列

详细链接:https://shop499704308.taobao.com/?spm=a1z38n.10677092.card.11.594c1debsAGeak
/// <summary>
/// 在DataTable中添加一序号列,编号从1依次递增
/// </summary>
/// <param >DataTable</param>
/// <returns></returns>
private DataTable AddSeriNumToDataTable(DataTable dt)
{
//需要返回的值
DataTable dtNew;
if (dt.Columns.IndexOf("序号") >= )
{
dtNew = dt;
}
else //添加一序号列,并且在第一列
{
int rowLength = dt.Rows.Count;
int colLength= dt.Columns.Count;
DataRow[] newRows = new DataRow[rowLength]; dtNew = new DataTable();
//在第一列添加“序号”列
dtNew.Columns.Add("序号");
for (int i = ; i < colLength; i++)
{
dtNew.Columns.Add(dt.Columns[i].ColumnName);
//复制dt中的数据
for (int j = ; j < rowLength; j++)
{
if (newRows[j] == null)
newRows[j] = dtNew.NewRow();
//将其他数据填充到第二列之后,因为第一列为新增的序号列
newRows[j][i+] = dt.Rows[j][i];
}
}
foreach (DataRow row in newRows)
{
dtNew.Rows.Add(row);
} }
//对序号列填充,从1递增
for (int i = ; i < dt.Rows.Count; i++)
{
dtNew.Rows[i]["序号"] = i + ;
} return dtNew; }
上一篇:prequeue receive queue backlog queue


下一篇:OpenStack的Resize和冷迁移代码解析及改进