How can I use linq to initialize an array of repeating elements?

I am currently using something like this to create a list of 10 objects:

myList = (from _ in Enumerable.Range(0, 10) select new MyObject {...}).toList() 

This is based on my python background, where I would write:

 myList = [MyObject(...) for _ in range(10)] 

Note that I want my list to contain 10 instances of my object, and not the same instance 10 times.

Is this still a smart way to do something in C #? Is there any need to do this in a simple cycle?

+7
source share
3 answers

The Fluent API in this case looks a little more readable, but it is not very easy to see the intent of your code:

 var list = Enumerable.Range(0, 10).Select(_ => new MyObject()).ToList(); 

Simple, if the cycle is quick and clear, but it also hides the list of creating objects from 10 elements

 List<MyObject> list = new List<MyObject>(); for (int i = 0; i < 10; i++) list.Add(new MyObject()); 

The best for readability is a builder who will describe your intentions

 public class Builder<T> where T : new() { public static IList<T> CreateListOfSize(int size) { List<T> list = new List<T>(); for (int i = 0; i < size; i++) list.Add(new T()); return list; } } 

Using:

 var list = Builder<MyObject>.CreateListOfSize(10); 

This decision is as fast as a simple cycle, and the intention is very clear. Also in this case we have the minimum code for writing.

+8
source

Personally, I think Enumerable.Repeat not overloaded. A convenient addition would be something like this:

 public static class EnumerableEx { public static IEnumerable<T> Repeat<T>(int amt, Func<T> producer) { for(var i = 0; i < amt; ++i) { yield return producer(); } } } 

so you can

 EnumerableEx.Repeat(10, () => new object()) //.ToList() 
+4
source

You can try:

 Enumerable.Range(0, 1000).Select(x => new MyObject()).ToArray(); 
+1
source

All Articles