tags:

views:

260

answers:

3

I have a 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?

+15  A: 
  List<int> list = Enumerable.Range(1, n).ToList();
Stan R.
+1 - I see you beat Adam by 24 seconds
JustLoren
+9  A: 
List<int> list = Enumerable.Range(1, n).ToList();
Adam Robinson
+2  A: 

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.

OregonGhost
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.
Pavel Minaev
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.
OregonGhost
@Pavel: Because that's exactly what `Enumerable.Range` does.
Adam Robinson
@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.
Pavel Minaev