Search code examples
c#linqindexoutofboundsexception

What happened on my `Enumerable.Range(,)`?


What happened on my Enumerable.Range(,)? It produced a number 5030 which is out of range.

sellableItems is a small List<T>, I need to randomly pick 9 items from it.

Here is the code:

var targetIndexes = Enumerable.Range(i + 1, sellableItems.Count-1)
      .OrderBy(x => random.Next())
      .Take(9)
      .ToArray();

for (var j = 0; j < targetIndexes.Length; j++)
{
     ...
}

enter image description here


Solution

  • The Enumerable.Range method takes in two parameters - a starting value and a count.

    When you do: Enumerable.Range(i + 1, sellableItems.Count - 1), you are starting with the value 37 (i + 1) and a count of 4999 (sellableItems.Count - 1).

    Since each iteration in the call to Range increments the previous value by one (except the first iteration, which uses the starting value), the range will be from 37 to 5035.