0

I am doing a research paper over the multiple sorting methods in C#. To do this I need to create a list for sorting, then sort this list using the sort methods. The problem is i don't know an easy way to make a copy of this list without creating around 100 unique lists so i can effectively test each method.

-Is there an easy way to create multiple copies of a list in a efficient way.

-Is there a way to clear a list then re-populate it with the original list eliminating the need to create a lot of unique lists.

Thanks in advance.

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
  • `var list2 = list1.ToList()` ? – ProgrammingLlama Oct 29 '18 at 01:59
  • one tip i have : allocate enough space for the list by specifying a capacity in its constructor. This way the list does not need to reallocate the list while adding items – jazb Oct 29 '18 at 02:03
  • Possible duplicate of [How do I clone a generic list in C#?](https://stackoverflow.com/questions/222598/how-do-i-clone-a-generic-list-in-c) – Dinh Tran Oct 29 '18 at 02:06

2 Answers2

1

Sample list:

var list1 = new List<string>();

-Is there an easy way to create multiple copies of a list in a efficient way.

var list2 = list1.ToList();

-Is there a way to clear a list then re-populate it with the original list eliminating the need to create a lot of unique lists.

var list2 = new List<string>(list1);
list2.Clear();
list2.AddRange(list1);
list2.Clear();
list2.AddRange(list1);

** Note that using .Clear the Capacity of the list isn't reset. Since we're just reusing the same source list without changing the size, I don't think this is a problem for you. If you were changing the number of test items between tests, I would initialize the list with a capacity to match the size of the largest list in your test set.

maccettura
  • 10,514
  • 3
  • 28
  • 35
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
  • Thanks i ended up figuring it out immediately after posting it i should've invested more time into trial and error thank you for your quick response. – G_Powersx08 Oct 29 '18 at 02:51
0

You can copy list to another as shown below

List<string> source = new List<string> { "one", "two", "three" };
List<string> target;

// simplest all source ellements from list constructor
target = new List<string>(source);

Another way using loop

// loop with condition
target = new List<string>();
foreach (string item in source)
{
   target.Add(item);                
}
Suraj Kumar
  • 5,547
  • 8
  • 20
  • 42