Can I initialize a list from an expression in a simple way, similar to Python?


Let’s say I have a function that returns an object:

public object toto() {}

Or in python:

def toto():
    return "something"

I want to initialize a list of n elements in a very simple way, in Python I would do:

l = [toto() for i in range(1, n+1)]

Is there a simple, similar way, of doing that in C#, avoiding loops ?

Thanks !

>Solution :

You can use Enumerable.Range:

var l = Enumerable.Range(0, n + 1).Select(i => "something" + i);

If you want to "consume" it you could use a foreach:

foreach(string s in l)

or create a new List<string> or string[]:

List<string> stringList = l.ToList();
string[] stringArray = l.ToArray();

That of courses also uses loops, just you don’t see them.

Note that if you often need to use it, you should really create a collection from it(as shown above). Otherwise you will always execute the LINQ query (Select is using deferred execution). Read this blog to understand the concept:

Leave a ReplyCancel reply