C# Get number ranges from list of numbers

Date: 2022-10-06
using System.Collections.Generic;
using System.Linq;

public interface INumberRange
{
	int Min { get; set; }
	int Max { get; set; }
}
public class NumberRange : INumberRange
{
	public int Min { get; set; }
	public int Max { get; set; }
}
public class RangeHelper
{
	public static INumberRange GetRange(int min, int max) => new NumberRange { Min = min, Max = max };

	public static IEnumerable<INumberRange> FindRanges(IEnumerable<int> input)
	{
		if (!input.Any()) yield break;
		var sortedList = input.OrderBy(x => x);
		var first = sortedList.FirstOrDefault();
		var range = GetRange(first, first);

		foreach (var item in sortedList)
		{
			if (range.Max == item || range.Max == item - 1)
			{
				range.Max = item;
				continue;
			}
			var oldRange = range;
			range = GetRange(item, item);
			yield return oldRange;
		}
		yield return range;
	}
}

68270cookie-checkC# Get number ranges from list of numbers