PageRange[] ComputeWrittenPageRanges(SparseIntArray writtenPages) { var pageRanges = new List <PageRange> (); int start = -1; int end = -1; int writtenPageCount = writtenPages.Size(); for (int i = 0; i < writtenPageCount; i++) { if (start < 0) { start = writtenPages.ValueAt(i); } int oldEnd = end = start; while (i < writtenPageCount && (end - oldEnd) <= 1) { oldEnd = end; end = writtenPages.ValueAt(i); i++; } var pageRange = new PageRange(start, end); pageRanges.Add(pageRange); start = end = -1; } return(pageRanges.ToArray()); }