0

I have array list named intArray. I need to get sublist of that arraylist and i know there is a method which takes two parameters: starting index and count. But i wanna implement a method by taking two parameters: lower index and higher index. Is there any way to do like this?

For e.g this is the arraylist :

int[] intArr = { 1, 2, 3, 4, 5, 6 };

So if we specify a method for e.g displayArray(1,4) //1 is lower index and 4 is higher index. so it should display elements from 1st index to 4th index.

Thanks!!!

  • you should at least try... please post some code that doesn't work for you. – silver Jul 21 '15 at 06:12
  • Try this : int[] intArr = { 1, 2, 3, 4, 5, 6 }; int lowIndex = 1; int highIndex = 4; int[] results = intArr.Skip(lowIndex).Take(highIndex - lowIndex + 1).ToArray(); – jdweng Jul 21 '15 at 06:32

1 Answers1

0

First thing's first, you have an array, not an ArrayList (ArrayList's are dynamic and resizable). But to clarify on your question, your method should be getting a sub list rather than displaying one if I understand your predicament correctly.

So you have to create a local array (in your what should be a getSubList() function instead of a displayArray function and return that. This will require a simple loop:

    for (int i = lowerIndex; i <= higherIndex; i++){
        ...read your array and add values to new array...
    }

Also, you should consider whether or not the indices that are passed in are valid (ex. we wouldn't want a negative index or an index greater than the size of the array) but this is just to make sure the function is safe from potentially crashing your program. You might need to consider one more parameter (since you are dealing with arrays) to prevent "bad" indices. This would be the length of the array.

fahimg23
  • 86
  • 4