0

I have to add about 3000 Elements to more than 20 Lists. The code that I am using:

LastChange = new List<string>();
LastChange.AddRange(Enumerable.Repeat("/", 3000));

same for more than 20 Lists...

Is there any "fastest way" to add "/" to the Lists or that is the best solution. Thanks in Advance...

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • 2
    `LastChange = new List(3000);` will be a little bit better: we allocate memory for `3000` items in order to avoid dynamic reallocation – Dmitry Bychenko Nov 02 '21 at 08:27
  • @DmitryBychenko thanks. Could you please write the complete answer ?! –  Nov 02 '21 at 08:27
  • Why not [`LastChange = Enumerable.Repeat("/", 3000).ToList()`](https://stackoverflow.com/a/1120733/7831383)? I don't really get the point in using `AddRange` when your list isn't an existing list – Rafalon Nov 02 '21 at 11:49

1 Answers1

3

A bit better solution is to allocate memory for 3000 items in the constructor in order to avoid memory reallocation:

 LastChange = new List<string>(3000);

 LastChange.AddRange(Enumerable.Repeat("/", 3000)); 

You can go further and get rid of IEnumerator<T> in Enumerable.Repeat:

 int count = 3000;

 LastChange = new List<string>(count);

 // compare to 0 is a bit faster then 3000
 for (int i = count - 1; i >= 0; --i)
   LastChange[i] = "\";        
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215