Home > Mobile >  Is there any easy way to clone all elements of a list inside itself?
Is there any easy way to clone all elements of a list inside itself?

Time:07-30

For example,

new List<int>{1,2,3,4} -> new List<int>{1,2,3,4,1,2,3,4}

Of course, I know it can be easy with a loop. But is there any more efficient way to do this?

CodePudding user response:

If you want to modify the existing list, you can do;

var list = new List<int>{1,2,3,4};
list.AddRange(list.ToList());

Note that it is necessary to copy the list (with ToList() or some other way), otherwise you end up modifying the same list while AddRange iterate over it to add elements.

If you want to create a new list, use Concat

var list = new List<int>{1,2,3,4};
var newList = list.Concat(list).ToList();

CodePudding user response:

You can use .AddRange() method,

List<int> input = new List<int>(){1,2,3,4};
var result = new List<int>(input);
result.AddRange(input);

Console.WriteLine(string.Join(", ", result));

If you want to include in the same List, then you can directly apply .AddRange() to input list itself.

input.AddRange(input);

CodePudding user response:

You are looking for AddRange:

list.AddRange(new List<yourtype>(list));

In the code above I have cloned list because under the hood, there must be a loop that traverses list's elements and add them to itself. So, in theory I can imagine cases of looping the list and infinitely adding the newly added elements, but when you do actual coding, it's worth testing whether

list.AddRange(list);

also works well. If so, then cloning the list is unnecessary. If not, then you need to clone.

  • Related