gpt4 book ai didi

c# - 向 DataTable 添加多行

转载 作者:太空狗 更新时间:2023-10-29 18:29:15 25 4
gpt4 key购买 nike

我知道有两种方法可以将包含数据的新行添加到 DataTable

string[] arr2 = { "one", "two", "three" };
dtDeptDtl.Columns.Add("Dept_Cd");

for (int a = 0; a < arr2.Length; a++)
{
DataRow dr2 = dtDeptDtl.NewRow();
dr2["Dept_Cd"] = DeptCd[a];
dtDeptDtl.Rows.Add(dr2);
}

for (int a = 0; a < arr2.Length; a++)
{
dtDeptDtl.Rows.Add();
dtDeptDtl.Rows[a]["Dept_Cd"] = DeptCd[a];
}

上述两种方法都会给我相同的结果,即一二三将在单独的行中添加到 DataTable 中。

但我的问题是,这两个步骤之间有什么区别,哪个步骤在性能方面更好?

最佳答案

一些反编译观察结果

在这两种情况下,都使用了 System.Data.DataRowCollection.Add 方法的不同重载。

第一种方法使用:

public void Add(DataRow row)
{
this.table.AddRow(row, -1);
}

第二种方法将使用:

public DataRow Add(params object[] values)
{
int record = this.table.NewRecordFromArray(values);
DataRow dataRow = this.table.NewRow(record);
this.table.AddRow(dataRow, -1);
return dataRow;
}

现在,看看这只小野兽:

internal int NewRecordFromArray(object[] value)
{
int count = this.columnCollection.Count;
if (count < value.Length)
{
throw ExceptionBuilder.ValueArrayLength();
}
int num = this.recordManager.NewRecordBase();
int result;
try
{
for (int i = 0; i < value.Length; i++)
{
if (value[i] != null)
{
this.columnCollection[i][num] = value[i];
}
else
{
this.columnCollection[i].Init(num);
}
}
for (int j = value.Length; j < count; j++)
{
this.columnCollection[j].Init(num);
}
result = num;
}
catch (Exception e)
{
if (ADP.IsCatchableOrSecurityExceptionType(e))
{
this.FreeRecord(ref num);
}
throw;
}
return result;
}

特别注意 this.columnCollection[i][num] = value[i];,它将调用:

public DataColumn this[int index]
{
get
{
DataColumn result;
try
{
result = (DataColumn)this._list[index];
}
catch (ArgumentOutOfRangeException)
{
throw ExceptionBuilder.ColumnOutOfRange(index);
}
return result;
}
}

继续前进,我们发现实际上 _list 是一个 ArrayList:

private readonly ArrayList _list = new ArrayList();

结论

为了总结以上内容,如果您使用 dtDeptDtl.Rows.Add(); 而不是 dtDeptDtl.Rows.Add(dr2);,您将性能下降会随着列数的增加呈指数增长。导致降级的原因是调用 NewRecordFromArray 方法,该方法遍历 ArrayList

注意:如果您向表中添加 8 列并在 for 循环 1000000 次中进行一些测试,则可以轻松测试。

关于c# - 向 DataTable 添加多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18462915/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com