I have an ordered array of integer values: 10, 11, 12, 13, 15, 16, 19 and I need to write a dash between first and last consecutive values when there are more than two consecutive values (10-13). Between other values I need to write a comma and whitespace. Output for this input must be 10-13, 15, 16, 19. I wrote a method that implements this:
class Program
{
private static string AddDashesBetweenConsecutiveNumbers(int[] orderedArray)
{
if (orderedArray.Length == 0 || orderedArray == null)
{
return string.Empty;
}
var groupedArray = orderedArray.Select((x, i) => new { Difference = i - x, Value = x })
.GroupBy(x => x.Difference)
.Select(group => group.Select(a => a.Value))
.Select(arr => arr.Count() > 2
? $"{arr.First()}-{arr.Last()}"
: string.Join(", ", arr));
return string.Join(", ", groupedArray);
}
static void Main(string[] args)
{
int[] array = { 10, 11, 12, 13, 15, 16, 19 };
Console.WriteLine(AddDashesBetweenConsecutiveNumbers(array)); // Output: "10-13, 15, 16, 19"
}
}
What I wrote seems to work, but this code has some disadvantages, especially in readability of the LINQ expression. So if you have any ideas how to improve this method or have better or alternative solution, that would be great to find out.