是否可以在C#中将队列数据添加到DataTable?

时间:2012-07-07 07:02:16

标签: c# data-structures datatable queue

我正在队列中添加项目<“string”>“异步到Queue.Instead of 逐行插入,使用INSERT查询为Queue的每个数据,当 if(evtLogQueue.Count == 1000)时,我想将这些项添加到DataTableOnly。因此,使用 BulkCopy 到SQLServerDB可以进一步使用DataTable进行批量插入。

我想知道这可能吗?如果是,那么如何?或任何其他建议?

示例代码:

static Queue<string> evtLogQueue = new Queue<string>();

public static void AddItemsToQueue(string itm)
        {

            evtLogQueue.Enqueue(itm);
            Console.WriteLine("Length of Queue:" + evtLogQueue.Count);

        }

2 个答案:

答案 0 :(得分:1)

是的,您可以通过向AddItemsToQueue(string itm)方法添加一些代码来实现此目的。

public static void AddItemsToQueue(string itm)
    {
        evtLogQueue.Enqueue(itm);
        // Add the following code
        if (evtLogQueue.Count == 1000)
        {
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add("Log");
            foreach (var log in evtLogQueue)
            { 
                DataRow dr = dataTable.NewRow();
                dr["Log"] = log;
                dataTable.Rows.Add(dr);
            }
            evtLogQueue.Clear();     // Most probably you will also need to clear the queue.
            SendBulkData(dataTable); // Send the bulk data
        }
    }

答案 1 :(得分:0)

它可能。

在AddItemsToQueue(string itm)中检查队列中元素的数量。

获得数字为1000后,运行for循环并将数据插入数据表。

请检查下面提到的批量复制链接

http://www.codeproject.com/Articles/16922/SQL-Bulk-Copy-with-C-Net

如果您仍然遇到任何问题,请告诉我。