Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

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?

like image 850
Eric Avatar asked Nov 25 '12 16:11

Eric


2 Answers

You can try:

Enumerable.Range(0, 1000).Select(x => new MyObject()).ToArray();
like image 106
FLCL Avatar answered Oct 12 '22 00:10

FLCL


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.

like image 21
Sergey Berezovskiy Avatar answered Oct 12 '22 01:10

Sergey Berezovskiy