2

I have this code:

List<int> list = new List<int>();
for (int i = 1; i <= n; i++)
    list.Add(i);

Can I create this List<int> in one line with LINQ?

3 Answers 3

20
List<int> list = Enumerable.Range(1, n).ToList();
Sign up to request clarification or add additional context in comments.

Comments

12
List<int> list = Enumerable.Range(1, n).ToList();

Comments

3

If you need a lot of those lists, you might find the following extension method useful:

public static class Helper
{
    public static List<int> To(this int start, int stop)
    {
        List<int> list = new List<int>();
        for (int i = start; i <= stop; i++) {
            list.Add(i);
        }
        return list;
    }
}

Use it like this:

var list = 1.To(5);

Of course, for the general case, the Enumerable.Range thing the others posted may be more what you want, but I thought I'd share this ;) You can use this next time your Ruby-loving co-worker says how verbose C# is with that Enumerable.Range.

4 Comments

If you're defining a general-purpose extension method like this, why not make it return IEnumerable<int> rather than List<int>? The established convention for ranges pretty much everywhere is that they're lazy.
Because it was asked for a List<int>, not for an IEnumerable<int>. I just wrote this for this question as a general sample how this could be shortened. And to show off to your Ruby co-worker, you would want to avoid the extra ToList call ;) Now of course, if you think this method is worth being a general-purpose method, go ahead and let it return IEnumerable<int>. This should even allow you to make it into an iterator block, instead of manually creating the list.
@Pavel: Because that's exactly what Enumerable.Range does.
@Adam: I think the point here is mainly that 1.To(10) looks cuter than Enumerable.Range(1, 10). In Ruby, IIRC, to also returns a lazy sequence rather than eagerly filled collection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.