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

Time:11-16

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 !

CodePudding user response:

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)
{
    Console.WriteLine(s);
}

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: https://codeblog.jonskeet.uk/2010/03/25/just-how-lazy-are-you/

  • Related