There is a certain array of numbers, approx. [1,2,3,4,6,7,12,14,15,16] It is necessary to convert it to a string of type "1-4,6,7,12,14-16"
How to do it?
Probably, my solution is not very optimized, but something is better than nothing ...
var intArray = new int[] { 1, 2, 3, 4, 6, 7, 12, 14, 15, 16, 17, 19, 20, 22, 23, 24, 25, 26, 27 }; var orderedArray = intArray.OrderBy(x => x).ToList(); string result = String.Empty; int? lastNum = null; int? fistNum = null; for (int i = 0; i < orderedArray.Count; i++) { var endFlag = i == orderedArray.Count - 1; if (fistNum == null) { result += orderedArray[i].ToString(); fistNum = orderedArray[i]; lastNum = orderedArray[i]; continue; } var flaSequnce = orderedArray[i - 1] == orderedArray[i] - 1; if (flaSequnce) { lastNum = orderedArray[i]; if (!endFlag) continue; } if (!flaSequnce && fistNum != lastNum || endFlag) { string delim = "-"; if (lastNum != null) { delim = fistNum - lastNum == -1 ? "," : "-"; } result += (lastNum != null ? delim + lastNum : "") + (endFlag ? "" : "," + orderedArray[i]); fistNum = orderedArray[i]; lastNum = null; } } var mass = [1,2,3,4,6,7,12,14,15,16,17, 19,20 ,22,23,24,25,26,27]; //int[] function massToStr(mass) { var str = "" + mass[0]; //string var count = 0; //int for(var i = 1 /*int*/; i < mass.length; i++){ if(mass[i] == mass[i-1]+1){ count++; if(i == mass.length-1){ if(count < 2){ str += "," + mass[i]; }else{ str += "-" + mass[i]; } } }else { if(count == 0){ str += "," + mass[i]; }else if(count < 2){ str += ","+ mass[i-1] + "," + mass[i]; }else{ str += "-" + mass[i-1] + "," + mass[i]; } count = 0; } } return str; } console.log(massToStr(mass)); The js code (which was at hand) looks scary and is not optimized, but it works as it should.
Source: https://ru.stackoverflow.com/questions/792477/
All Articles
.Select(list => list.Count == 1 ? $"{list.First()}" : $"{list.First()}-{list.Last()}")and then put instring.Join(",", ...)- Andrew NOP