As designed. Assume the list has 10 elements, with index from 0 to 9
list.GetRange(0, 10) // returns elements at indexes 0,1,2,3,4,5,6,7,8,9
list.GetRange(1, 10) // returns elements at indexes 1,2,3,4,5,6,7,8,9,10. List[10] is out of range.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
hi
I was just working with List<T>.GetRange on your online c# compiler and it seems to be inconsistent when I input "list.GetRange(0,list.Count)" I receive the whole list as I should. But when I input " list.GetRange(1,list.Count)" I receive an out of bounds exception which I managed to solve by writing " list.GetRange(1,list.Count-2)" in order to get the range that I want.
Is this an intentional feature or a bug?
thanks for your time
As designed. Assume the list has 10 elements, with index from 0 to 9
list.GetRange(0, 10) // returns elements at indexes 0,1,2,3,4,5,6,7,8,9
list.GetRange(1, 10) // returns elements at indexes 1,2,3,4,5,6,7,8,9,10. List[10] is out of range.
See my .NET Fiddle
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
namespace ConsoleApp1
{
public class Program
{
public static void Main()
{
var monthNames = Enumerable.Range(1, 12)
.Select((index) => DateTimeFormatInfo.CurrentInfo.GetMonthName(index)).ToList();
Index indexer = new Index(monthNames.FindIndex(item => item.Equals("april",
StringComparison.OrdinalIgnoreCase)));
var fourMonths = monthNames.ByIndex(indexer.Value, 4);
Console.WriteLine(string.Join(",", fourMonths));
Console.WriteLine("");
List<int> list = new() { 1, 2, 3, 4, 5 };
Console.WriteLine($"list[^1] => {list[^1]}");
Console.WriteLine("");
var monthNamesArray = Enumerable.Range(1, 12).Select((index) =>
DateTimeFormatInfo.CurrentInfo.GetMonthName(index)).ToArray();
Range firstFourRange = ..4;
Console.WriteLine(string.Join(",", monthNamesArray[firstFourRange]));
}
}
static class Extensions
{
public static List<T> ByIndex<T>(this List<T> value, int startIndex, int endIndex) =>
value.GetRange(startIndex, endIndex);
}
}