0

How can you index from mid point of an array to the end point without specify the exact end point. So for example I have an array of {1,2,3,4,5,6} how can I index (find values of) [3] -> [5] (4-6). Its very clear in languages like python but I can't seem to find the answer for C# if there is a short and simple way please let me know thanks!

ill give you some more context, I have an array of items and want to get the items from the 2nd value too the end, however the end changes for all the lists, but it always starts from 2nd value.

  • `myArray.Skip(3).ToArray()`? – 41686d6564 stands w. Palestine Feb 22 '21 at 23:37
  • @41686d6564 so this would index from 3 to end of the list for any list? i thought .Skip was for foreach loops. – mathewsjoyyy Feb 22 '21 at 23:40
  • Not sure what you mean by "index". If you mean cut or slice, then yes. See: [`Skip()`](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.skip) and [`Take()`](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.take). – 41686d6564 stands w. Palestine Feb 22 '21 at 23:41
  • Note that C# makes a distinction between an *array* (a fixed-length collection of contiguous values), a *list* (a resizeable collection of values), and an *enumerable* object (any object that can produce a sequence of values, whether from a list, a random number generator, etc). A list *is* enumerable, and an array *is* enumerable. The *skip* method returns a new *enumerable*, which yields the remaining elements in the sequence. – Andrew Williamson Feb 22 '21 at 23:44
  • @41686d6564 ill give you some more context, I have an array of items and want to get the items from the 2nd value too the end, however the end changes for all the lists, but it always starts from 2nd value. – mathewsjoyyy Feb 22 '21 at 23:47
  • @AndrewWilliamson Ive added some more context to my post so its more clear what iam trying to do. – mathewsjoyyy Feb 22 '21 at 23:48
  • @mathewsjoyyy Again `var smallArray = bigArray.Skip(1).ToArray();` Did you try it? – 41686d6564 stands w. Palestine Feb 22 '21 at 23:49
  • @41686d6564 yeh,doesnt work – mathewsjoyyy Feb 22 '21 at 23:51
  • Well, "doesn't work" is not really a good description of a problem. What exactly happens when you run the code? Also, it does exactly what you described. [Proof](https://rextester.com/JKZ20210). – 41686d6564 stands w. Palestine Feb 22 '21 at 23:54

1 Answers1

1

If you are using C# 8.0 and higher you can use index range.

You can write something like myArray[3..^0]; to get anything from index 3 up to the end.

I suggest to read Indices and Ranges.

dropoutcoder
  • 2,627
  • 2
  • 14
  • 32