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 using LINQ?
+2
AndreyAkinshin
source
to share
3 answers
List<int> list = Enumerable.Range(1, n).ToList();
+20
Stan R.
source
to share
List<int> list = Enumerable.Range(1, n).ToList();
+12
Adam robinson
source
to share
If you need a lot of these lists, you can find the following extension method:
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 enumerated thing others have posted might be more than what you want, but I thought I'd share it;) You can use that next time your ruby-loving colleague speaks like verbose C # with this Enumerable.Range.
+3
OregonGhost
source
to share