score:10

Accepted answer

You can use this iterator block:

IEnumerable<int> CreateRange(int x1, int x2) {
  var increment = x2 > x1 ? 1 : -1;
  for (var i = x1; i != x2; i += increment)
    yield return i;
  yield return x2;
}

It's efficient and creating a range is just as clean as using Enumerable.Range:

CreateRange(10, 5).Select( ... )

score:3

You can do something like this:

//normal order works
int x1 = 5;
int x2 = 10;
int len = Math.Abs(x2 - x1) + 1;

var range = x1 < x2 ? Enumerable.Range(x1, len) : Enumerable.Range(x2, len).Reverse();

 //reverse order works (the same code for range)
 x1 = 10;
 x2 = 5;
 len = Math.Abs(x2 - x1) + 1;

 range = x1 < x2 ? Enumerable.Range(x1, len) : Enumerable.Range(x2, len).Reverse();

score:4

If you want to stick with single LINQ statement -

Enumerable.Range(0, Math.Abs(x2 - x1) + 1).Select(i => x1 + i * Math.Sign(x2 - x1))

Related Articles