Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
{
    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/

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading