Jim Riddles
asked on
How to copy a List<string> in C# .NET5
I am attempting to copy a List<string> into a temporary variable to work on. However, when I call RemoveAt on the temporary variable, it appears to be affecting the original variable. How can I prevent this?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Hi,
If you want to copy the existing list, there is one Clone method in C# to duplicate it well. Read:
https://www.delftstack.com/howto/csharp/copy-a-list-in-csharp/
If you want to copy the existing list, there is one Clone method in C# to duplicate it well. Read:
https://www.delftstack.com/howto/csharp/copy-a-list-in-csharp/
ASKER
Thank you to all who participated. I chose Ryan's answer since it displayed code to assist me in solving my issue. I wanted to know if anybody had any insight as to which method is best practice.
Hi Jim,
You can always self-test which code performs better that best suit your actual case :)
Note: Change case 1 or case 2 based on your actual scenario.
You can always self-test which code performs better that best suit your actual case :)
Note: Change case 1 or case 2 based on your actual scenario.
using System.Diagnostics.Stopwatch
Stopwatch stopWatch = new Stopwatch();
TimeSpan ts;
//case 1
stopWatch.Start();
//put your code - first senario here...
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
ts = stopWatch.Elapsed;
// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine("RunTime " + elapsedTime);
//case 2
stopWatch.Start();
//put your code here - second senario here...
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
ts = stopWatch.Elapsed;
// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine("RunTime " + elapsedTime);
You can assign a variable under windows by reference or by value.
Assigning by reference means, that the new variable is just a reference to the old one what means in fact, that changes to the variable also affects the source.
Assigning by value means, that the new variable takes over the content of the old one, so changed on the new variable do NOT reflect back to the old variable.