CSharp · Console
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
var myList = new List<string> { "1", "3-6", "2", "8-10", "7", "11", "13-18", "12" };
var ranges = myList.Select(x=> new Range(x)).ToList();
ranges.Sort();//Order yourself!
//Display
foreach (var range in ranges) Console.WriteLine(range);
//One line with comma separator
Console.WriteLine(string.Join(", ", ranges));
}
public class Range : IComparable<Range>
{
// Simple ctor, with Customisable separator in case of Negative Value.
public Range(string input, char separator= '-') {
if (!input.Contains(separator))// Is it a range?
{//It's not then
if (int.TryParse(input, out int value))// Lets try to convert it to an integer
{// it's a int then
Min = value; Max = value; // both min and max
}
else
{// It's not a range and it's not an int! Scream!
throw new ArgumentException(input + " is not a valid input !");
}
}
else
{//It's a range
var parts = input.Split(new char[] { separator }, 2);// split in 2 on the separator
if (int.TryParse(parts[0], out int part1) && int.TryParse(parts[1], out int part2))// Both part are int?
{
Min = Math.Min(part1, part2); // min is the min and max the max.
Max = Math.Max(part1, part2); // It's easier to compute min/max than try to fix a bad input.
}
else {// It's look like a range but those are not int! Scream!
throw new ArgumentException(input + " is not a valid input !" );
}
}
}
public int Min { get; set; }
public int Max { get; set; }
// Comparing bound together. {1-1} < {1-2} < {1-6} < {2-2};
public int CompareTo(Range obj)
{
var mincomparer = this.Min.CompareTo(obj.Min);
var maxcomparer = this.Max.CompareTo(obj.Max);
return mincomparer == 0 ? maxcomparer : mincomparer;
}
public override string ToString()
{
return Min == Max ? Min.ToString() : Min + "-" + Max;
}
}
}