using System; public class Test { public static void Main() { Console.WriteLine(ConvertToRanges("1,2,3,4,8,9,10,15")); Console.WriteLine(ConvertToRanges("5,6,7,9,10,11,12,15,16")); } public static string ConvertToRanges(string pageNos) { string result=string.Empty; string[] arr1 = pageNos.Split(','); int[] arr = new int[arr1.Length]; for (int x = 0; x < arr1.Length; x++) // Convert string array to integer array { arr[x] = Convert.ToInt32(arr1[x].ToString()); } int start,end; // track start and end end = start = arr[0]; for (int i = 1; i < arr.Length; i++) { // as long as entries are consecutive, move end forward if (arr[i] == (arr[i - 1] + 1)) { end = arr[i]; } else { // when no longer consecutive, add group to result // depending on whether start=end (single item) or not if (start == end) result += start + ","; else result += start + "-" + end + ","; start = end = arr[i]; } } // handle the final group if (start == end) result += start; else result += start + "-" + end; return result; } }