question

yechielSulzbacher-3655 avatar image
0 Votes"
yechielSulzbacher-3655 asked AlexZhu-MSFT edited

List<T>.GetRange

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

dotnet-csharp
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

@VladZai-5446, is any update? Please check if the following answer works for you.

0 Votes 0 ·
Bruce-SqlWork avatar image
0 Votes"
Bruce-SqlWork answered

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.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

karenpayneoregon avatar image
0 Votes"
karenpayneoregon answered

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);
     }
 }




5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.