Reputation: 317
In python we have a range that can produce for an array with negative integers too.
For example:
In[4]: range(-2, 2+1)
Out[4]: [-2, -1, 0, 1, 2]
Is there an equivalent system in C#; I am aware of IEnumerable method, but upon trying it I get the following output:
//Rextester.Program.Main is the entry point for your code. Don't change it.
//Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
//Your code goes here
Console.WriteLine("Hello, world!");
int half_window = 2;
var mySeq1 = Enumerable.Range(-2, 2+1).ToArray();
foreach(var item in mySeq1)
Console.Write(item.ToString() + " ");
}
}
}
Produces the output:
Hello, world!
-2 -1 0
Is there already an inbuilt method that I can use to get the python's output ?
Upvotes: 5
Views: 4394
Reputation: 75
Enumerable.Range works like this
Enumerable.Range(STARTVALUE, How many to count up)
Example
Enumerable.Range(6, 10)
Would produce
arr[6,7,8,9,10,11,12,13,14,15,16]
that is, 10 elements starting from
If you want to count up to a surden point you'll have to write your own functionality. Something alike
MakeRange(int st, int end)
{
var range = st < 0 ? Math.Abs(st) + end + 1 : end-st;
return Enumerable.Range(st, range);
}
Hope this helped you
Upvotes: 0
Reputation: 6566
C#'s Enumerable.Range
takes a start value and a count - the number of elements to return, not an end value like in python. To get the equivalent return value to python, you need to call it as:
Enumerable.Range(start, end-start);
So in your case, the call would be
Enumerable.Range(-2, (2+1) - (-2));
which is the same as saying
Enumerable.Range(-2, 5);
The only caveat is you need to be careful that end-start
is not negative, otherwise Enumerable.Range
will throw an ArgumentOutOfRangeException
.
Upvotes: 0
Reputation: 2742
Exactly as cubrr says, the second parameter works slightly differently - if you wanted to write your own method that works exactly like the Python equivalent, you could use:
public static class MyEnumerable
{
public static IEnumerable<int> Range(int start, int stop)
{
for (int i = start; i < stop; i++)
yield return i;
}
}
Used as:
var result = MyEnumerable.Range(-2, 3); // -2, -1, 0, 1, 2
Upvotes: 1
Reputation: 13652
The second argument of Enumerable.Range
specifies the count of the elements to be generated, not the stop value.
Console.WriteLine("Hello, world!");
int half_window = 2;
var mySeq1 = Enumerable.Range(-2, 5).ToArray();
// ^
foreach(var item in mySeq1)
Console.Write(item.ToString() + " ");
Output:
Hello, world!
-2 -1 0 1 2
Upvotes: 9