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?
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?
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.