I've updated the code to output at most one instance of a value that appears in the input multiple times:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List<int> input = new List<int> { 5, 7, 8, 9, 10, 10, 15, 16, 17, 18, 20 };
string output = FormatIntegers(input);
Console.WriteLine(output); // Output: 5, 7-10, 15-18, 20
}
public static string FormatIntegers(List<int> integers)
{
if (integers.Count == 0)
{
return "";
}
integers.Sort();
StringBuilder formattedString = new StringBuilder();
int startRange = integers[0];
int count = 1;
for (int i = 1; i < integers.Count; i++)
{
if (integers[i] == integers[i - 1] + 1)
{
count++;
}
else if (count > 1 || integers[i] != integers[i - 1])
{
if (count > 1)
{
formattedString.AppendFormat("{0}-{1}, ", startRange, integers[i - 1]);
}
else
{
formattedString.AppendFormat("{0}, ", startRange);
}
startRange = integers[i];
count = 1;
}
}
if (count > 1 || integers[integers.Count - 1] != integers[integers.Count - 2])
{
formattedString.AppendFormat("{0}, ", startRange);
}
if (formattedString.Length > 0)
{
int lastCommaIndex = formattedString.ToString().LastIndexOf(',');
formattedString.Remove(lastCommaIndex, 1);
}
return formattedString.ToString();
}
}
Now, the function outputs at most one instance of a value that appears in the input multiple times. For example, if the input list contains the value 10 twice, the output string will contain 10 only once.