Initialize list <T> with non-null values

I am looking for a way to initialize a variable of type List with a set of values ​​(in C #). Yes, there is an object initialization, but this requires a new object for each value, and I would prefer to avoid it.

Here is an example:

class MyObject { public string Name {get;set;} } List<MyObject> OldNames = new List<MyObject>(10); List<MyObject> NewNames = new List<MyObject>(5); 

It's fine and dandy, but OldNames contains 10 null references to an object of type MyObject.

Using a list initializer, I could do this:

 List<MyObject> OldNames = new List<MyObject>{ new MyObject(), new MyObject(), new MyObject(), etc. 

It’s such a pain because I have many list variables and various sizes for initialization (for example, one variable is a list of 26 objects. Yes, I could write a function or extension to do this initialization for me (in the loop where I provide size), but again this code, which I don’t necessarily want to write.

I hope there is some kind of lamdba or LINQ expression or something to initialize a list of objects for values ​​instead of zeros.

Thanks!

+6
source share
4 answers

Use the Enumerable.Range LINQ method to specify the number of iterations.

 List<MyObject> NewNames = Enumerable.Range(1,5).Select(i => new MyObject()).ToList(); 

The number 1 is arbitrary here, since the index is not used in any way.

+14
source

Just a quick thought ... you can use Enumerable.Repeat ... just not the way it was before. This will work:

 var query = Enumerable.Repeat<Func<MyObject>>(() => new MyObject(), count) .Select(x => x()) .ToList(); 

I do not suggest you do this, but it is an interesting alternative to Enumerable.Range .

+3
source

Create a create and initialize function.

 public List<T> CreateAndInitialize<T>(int size, Func<int, T> init) { var result = new List<T>(size); for (int i = 0; i < size; ++i) result.Add(init(i)); return result; } 

Then

 List<MyObject> newNames = CreateAndInitialize(15, i => return new MyObject()); 

I decided to pass the index of the object in the init delta so that you can take this into account if necessary.

+1
source

It looks like you simply did not notice the brackets () after the new declaration.

 private List<MyObject> ObjectList = new List<MyObject>() { new MyObject() { property1= Value1, property2 = "Value2"}, new MyObject() { property1= Value1, property2 = "Value2"} }; 
0
source

Source: https://habr.com/ru/post/946602/


All Articles