Sudha
Sudha

Reputation: 503

Add multiple rows into datatable with the same data without looping

Is there a way to add multiple rows with the same content without loop?

The following is the code I am currently using to achieve this.

        DataTable dtMessageDetails = new DataTable("Private Message Details");
        for (int i = 0; i < 10; i++)
        {
            dtMessageDetails.Rows.Add("65E6BD38-2806-S15G-9DC5-9DE908333996", 3, 0, "News", "News", Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd")), "Publish", "mes", 0, 0, 0, "null", "null", "Active");
        }

And my datatable should looks like

enter image description here

I want to replace loop with some other approach may be LINQ.

Upvotes: 0

Views: 5107

Answers (2)

Alex Filipovici
Alex Filipovici

Reputation: 32571

In addition to @lazyberezovsky's answer, I recommend you to use the DataRowCollection.Add Method (DataRow) method overload, which is slightly faster:

var itemArray = new object[] { 
    "65E6BD38-2806-S15G-9DC5-9DE908333996", 3, 0, "News", "News", 
    Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd")),
    "Publish", "mes", 0, 0, 0, "null", "null", "Active" };

for (int i = 0; i < 10000; i++)
{
    var r = dtMessageDetails.NewRow();
    r.ItemArray = itemArray;
    dtMessageDetails.Rows.Add(r);
}

If you intend to add the same rows to a new DataTable instance through your code, you might also get some performance improvement if you use the DataTable.Copy Method. Just create the rows above once in your code, then use the following to populate another datatable:

var dtMessageDetailsCopy = dtMessageDetails.Copy();

Upvotes: 2

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236268

Linq is for querying data, not for inserting. You can prepare data with linq, but you will use same loop for adding rows, which will not be any faster. Thus you are inserting same data, I suggest you to prepare these data instead of creating new items array on each iteration:

DataTable dtMessageDetails = new DataTable("Private Message Details");
object[] items = { "65E6BD38-2806-S15G-9DC5-9DE908333996", 3, 0, "News", "News", 
                   Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd")), 
                   "Publish", "mes", 0, 0, 0, "null", "null", "Active" };

for (int i = 0; i < 10; i++)    
    dtMessageDetails.Rows.Add(items);

Upvotes: 3

Related Questions