At present, I'm using something like this to build a list of 10 objects:
myList = (from _ in Enumerable.Range(0, 10) select new MyObject {...}).toList()
This is based off my python background, where I'd write:
myList = [MyObject(...) for _ in range(10)]
Note that I want my list to contain 10 instances of my object, not the same instance 10 times.
Is this still a sensible way to do things in C#? Is there a cost to doing it this way over a simple for loop?
You can try:
Enumerable.Range(0, 1000).Select(x => new MyObject()).ToArray();
Fluent API looks a little more readable in this case, but its not very easy to see the intent of your code:
var list = Enumerable.Range(0, 10).Select(_ => new MyObject()).ToList();
Simple if loop is fast and easy to understand, but it also hides intent - creating list of 10 items
List<MyObject> list = new List<MyObject>();
for (int i = 0; i < 10; i++)
list.Add(new MyObject());
The best thing for readability is a builder, which will describe your intent
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;
}
}
Usage:
var list = Builder<MyObject>.CreateListOfSize(10);
This solution is as fast, as simple loop, and intent is very clear. Also in this case we have minimum amount of code to write.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With