CSharp C# Make a non-referenced copy of a string List
Note: this will not work on class objects just primitives like string and int
Key section:
//Make a "copy" - not a reference - of the original list:
List<string> Copy_List = new List<string>(new List<string>(Original_List));
|
Output from example:
Show Original_List before changes:
One
Two
Three
Four
Show Copy_List before changes:
One
Two
Three
Four
Show Original_List after change to original list:
Note: 2nd ordinal value, "Two" will be gone from this list.
One
Three
Four
Show Copy_List after change to original list:
Note: 2nd ordinal value, "Two" will NOT be gone from this "copy" of the "original" list.
One
Two
Three
Four
|
Code:
void Main()
{
//First set up Original list of values:
List<string> Original_List = new List<string>();
Original_List.Add("One");
Original_List.Add("Two");
Original_List.Add("Three");
Original_List.Add("Four");
//Make a "copy" - not a reference - of the original list:
List<string> Copy_List = new List<string>(new List<string>(Original_List));
//Show the values before the change:
Console.WriteLine("Show Original_List before changes:");
Show_Values(Original_List);
Console.WriteLine("Show Copy_List before changes:");
Show_Values(Copy_List);
//Remove the 2nd string, ordinal 1, "Two", from the original but not the copy:
Original_List.RemoveAt(1);
//Show the values after the change:
Console.WriteLine("Show Original_List after change to original list:");
Console.WriteLine(" Note: 2nd ordinal value, \"Two\" will be gone from this list.");
Show_Values(Original_List);
Console.WriteLine("Show Copy_List after change to original list:");
Console.WriteLine(" Note: 2nd ordinal value, \"Two\" will NOT be gone from this \"copy\" of the \"original\" list.");
Show_Values(Copy_List);
}
public void Show_Values(List<string> ListNow)
{
foreach(string StringNow in ListNow)
{
Console.WriteLine(StringNow);
}
}
|
No comments:
Post a Comment