我已经重写了你的代码:
public static string[] FormatInts(int[] ints) { Array.Sort(ints); List values = new List (); for (int i = 0; i < ints.Length; i++) { int groupStart = ints[i]; int groupEnd = groupStart; while (i < ints.Length - 1 && ints[i] - ints[i + 1] == -1) { groupEnd = ints[i + 1]; i++; } values.Add(string.Format(groupEnd == groupStart ? "{0}":"{0} - {1}", groupStart, groupEnd)); } return values.ToArray(); }
然后:
///////////////// int[] myInts = { 1,2,3,5,7,9,10,11,12,14 }; string[] result = FormatInts(myInts); // now result haves "1-3", "5", "7", "9-12", "14"