Auto-initializing C# lists

C#.NetListCollections

C# Problem Overview


I am creating a new C# List (List<double>). Is there a way, other than to do a loop over the list, to initialize all the starting values to 0?

C# Solutions


Solution 1 - C#

In addition to the functional solutions provided (using the static methods on the Enumerable class), you can pass an array of doubles in the constructor.

var tenDoubles = new List<double>(new double[10]);

This works because the default value of an double is already 0, and probably performs slightly better.

Solution 2 - C#

You can use the initializer:

var listInt = new List<int> {4, 5, 6, 7};
var listString = new List<string> {"string1", "hello", "world"};
var listCustomObjects = new List<Animal> {new Cat(), new Dog(), new Horse()};

So you could be using this:

var listInt = new List<double> {0.0, 0.0, 0.0, 0.0};

Otherwise, using the default constructor, the List will be empty.

Solution 3 - C#

Use this code:

Enumerable.Repeat(0d, 25).ToList();
new List<double>(new double[25]);     //Array elements default to 0

Solution 4 - C#

One possibility is to use Enumerable.Range:

int capacity;
var list = Enumerable.Range(0, capacity).Select(i => 0d).ToList();

Another is:

int capacity;
var list = new List<double>(new double[capacity]);

Solution 5 - C#

A bit late, but maybe still of interest: Using LINQ, try

var initializedList = new double[10].ToList()

...hopefully avoiding copying the list (that's up to LINQ now).

This should be a comment to Michael Meadows' answer, but I'm lacking reputation.

Solution 6 - C#

For more complex types:

List<Customer> listOfCustomers =
        new List<Customer> {
            { Id = 1, Name="Dave", City="Sarasota" },
            { Id = 2, Name="John", City="Tampa" },
            { Id = 3, Name="Abe", City="Miami" }
        };

from here: David Hayden's Blog

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJasCavView Question on Stackoverflow
Solution 1 - C#Michael MeadowsView Answer on Stackoverflow
Solution 2 - C#Jhonny D. Cano -Leftware-View Answer on Stackoverflow
Solution 3 - C#SLaksView Answer on Stackoverflow
Solution 4 - C#jasonView Answer on Stackoverflow
Solution 5 - C#DanielView Answer on Stackoverflow
Solution 6 - C#ColinView Answer on Stackoverflow