我想将数据添加到DataTable中已经存在的DataRow中。
这样做的想法是,不复制已经存在的数据。

在编写一些测试时,我发现直接插入数据比将现有数据和新数据都复制到新行并添加该行要慢得多。

还是我做错了?

首先,我用初始数据创建一个数据表。

填写初始数据:

DataTable table1 = new DataTable();
int count = 15;
for (int i = 0; i < count; i++)
{
    table1.Columns.Add("hallo" + i, i % 2 == 0 ? typeof(int) : typeof(string));
}
int newStartIndex = table1.Columns.Count;
DateTime pre = DateTime.Now;
for (int i = 0; i < 100000; i++)
{
    DataRow row = table1.NewRow();
    for (int j = 0; j < table1.Columns.Count; j++)
    {
        if (j % 2 == 0)
        {
            row[j] = 502;
        }
        else
        {
            row[j] = "test";
        }
    }
    table1.Rows.Add(row);
}


之后,我再添加15列和数据。

for (int i = count; i < 2 * count; i++)
{
    table1.Columns.Add("hallo" + i, i % 2 == 0 ? typeof(int) : typeof(string));
}

foreach( DataRow row in table1.Rows)
{
    for (int j = newStartIndex; j < table1.Columns.Count; j++)
    {
        if (j % 2 == 0)
        {
            row[j] = 502;
        }
        else
        {
            row[j] = "test";
        }
    }
}


当花费时间时,它表明插入数据(应该与最初添加的数据完全相同的数据)花费的时间约为初始填充时间的10倍。

现在我尝试了相同的复制数据:

List<object[]> toAdd = new List<object[]>();

foreach (DataRow row in table1.Rows)
{
    object[] newArray = new object[table1.Columns.Count];
    Array.Copy(row.ItemArray, newArray, count);
    for (int j = newStartIndex; j < table1.Columns.Count; j++)
    {
        if (j % 2 == 0)
        {
            newArray[j] = 502;
        }
        else
        {
            newArray[j] = "test";
        }
    }
    toAdd.Add(newArray);
}
table1.Rows.Clear();
foreach( var o in toAdd)
{
    table1.Rows.Add(o);
}


这大约是初始填充时间的2.​​5倍,这比直接插入要快得多。

我认为以某种方式添加数据必须比复制所有内容并重新添加数据更快。

我尝试写入DataRow.ItemArray,但是在此之后所做的更改将不会出现在DataTable中。

有任何想法吗?也许对此行为有解释?

最佳答案

我不确定您为什么要进行这样的努力,并且可能有您自己的原因。
但是,语法不完全正确,您是否曾研究过...

DataTable.Clone()  // to make a copy

DataTable.Merge()  // to merge one datatable all rows (w/Matching columns) into another

DataView oDV = YourDataTable.DefaultView
oDV.Filter = ...
DataTable newTable = oDV.ToTable()

关于c# - 将数据添加到现有DataTable的DataRow中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4794137/

10-12 22:14
查看更多