Disclaimer: A very similar question was already asked in a Python context here. This is about C#.
I have an enumeration containing integers such as:
[1, 2, 3, 4, 7, 8, 10, 11, 12, 13, 14]
I'd like to obtain a string putting out the ranges of consecutive integers:
1-4, 7-8, 10-14
I came up with:
public static void Main()
{
System.Diagnostics.Debug.WriteLine(FindConsecutiveNumbers(new int[] { 1,2, 7,8,9, 12, 15, 20,21 }));
}
private static string FindConsecutiveNumbers(IEnumerable<int> numbers)
{
var sb = new StringBuilder();
int? start = null;
int? lastNumber = null;
const string s = ", ";
const string c = "-";
var numbersPlusIntMax = numbers.ToList();
numbersPlusIntMax.Add(int.MaxValue);
foreach (var number in numbersPlusIntMax)
{
var isConsecutive = lastNumber != null && lastNumber + 1 == number;
if (!isConsecutive)
{
if (start != null)
{
if (sb.Length > 0) { sb.Append(s); }
if (start == lastNumber)
{
sb.Append(start); ;
}
else
{
sb.Append(start + c + lastNumber); ;
}
}
start = number;
}
lastNumber = number;
}
return sb.ToString();
}
This algorithm works for ordered input. Is there a built-in/LINQ/shorter C# way of doing this?