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.
Sergey Berezovskiy
source share