AndreyAkinshin
AndreyAkinshin

Reputation: 19011

Create single permutation with LINQ in C#

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?

Upvotes: 2

Views: 807

Answers (3)

Stan R.
Stan R.

Reputation: 16065

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

Upvotes: 20

OregonGhost
OregonGhost

Reputation: 23759

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.

Upvotes: 3

Adam Robinson
Adam Robinson

Reputation: 185593

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

Upvotes: 12

Related Questions