Solution for Getrange error when accessing elements outside the list

Asked

Viewed 65 times

-3

By calling the GetRange of a list, where it calls 10 out of 10 values from the list at a time, but the following error:

Offset and length Were out of Bounds for the array or Count is Greater than the number of Elements from index to the end of the source Collection.

As he calls 10 out of 10 if you finish the list and do not contain the 10 it happens the error, how can I do so when calling 10 if it does not contain the 10 inside the list it catches the rest it contains thus avoiding the error.

 foreach (var item in lst.GetRange(count, index))
        {
          //count e index e incrementado +10 quando passa novamente começa do (0,9)
         //aqui inseri os valores no cshtml
        }
  • And pq inside the foreach I’m writing an html where it takes the values of the item and arrow in the value of the tag and makes the return to an ajax in html form

  • Could you post the rest of the code? Maybe Skip() and Take() can suit you better. Where is coming from the values of count and of index? What do you really want to do? Maybe you have a better alternative

  • In general : This is within this method Get countudoindex(int countIndex, int index) ,in the view has an ajax that is executed if $('window.scroll') arrives at the end of the page. Which calls url: '/Get content? countIndex='+countIndex+'&index='+index+'', these Count and index values are passed via parameter to the method by js , within the method Get countudoindex I go through the database and take the values and save in this list "lst", I want him to search 10 out of 10 on that list as long as there’s data on it, it’s all working but it’s coming off the list.

  • Then I would do with .Take() and .Skip(). Your example would look something like this: var listaNova = lst.Skip(10).Take(10).ToList();`. In that case he would skip 10 items and get the next 10. An example would be this from here

  • Really with take and Skip it worked perfectly when it finishes the items and tries to access out of the list it does not error just returns blank :) Thanks!

1 answer

0


The error is clear, as you said yourself. With the .GetRange() you are passing the value above the amount of items in the list.

To continue using .GetRange(), you would have to treat for it not to occur.

However, from what you explained in the comments, I believe that the .Take() and .Skip() can suit you better.

.Take()
Returns a specified number of contiguous elements from the beginning of a sequence.

.Skip()
Skips a specified number of elements in a sequence and then returns the remaining elements.

An example with the use would be:

lst.Skip(10).Take(10).ToList()

Where the .Skip() is "skipping" 10 items and the .Take() is selecting the next 10 items.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.