[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 547
  • Last Modified:

Fastest, Easiest, Most Efficient way to duplicate a Datatable column?

Hi Experts,

Quick question - Hopefully I don't know it, but what is the fastest way to duplicate a column in a datatable with all the data?

In other words, suppose I have a datatable with a column called "col1" populated with values. What I would like is to add a new column to my datatable called, say, col1_copy and have it have all the exact same values as col1.

I'm hoping there is a faster way than just:
Add column to Datatble with same structure as col1
Loop through datarows and copy from one column to the other
since my datatables are ENORMOUS and I'm duplicating quite a few columns and, so, updating the datatable value-by-value seems to be very slow...

PLEASE let me know the fastest, most efficient way to do this???

1 Solution
Luis PérezSoftware Architect in .NetCommented:
How do you fill originally the data in your "col1" column? Because the fastest way would be to fill the col1_copy column from the origin of data. I mean, if you have a SELECT returning the data to your datatable, add a new column to the SELECT with the AS col1_copy clause. This would be the fastest way.

If you want to do it exclusively into .Net code, then a loop will be mandatory. You can use LINQ to do the stuff, be although the syntax will be LINQ and probably you can do it in only 1 line of code, internally it will execute a Loop thru all values.

Hope that helps.
If the above comment does not apply then I think looping and copying is the only option( I am not sure if LINQ can help here)

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now