Overlapping Ranges Check for Overlapping

.net, c#, intersect, list, range

Solution

First merge numbers and then check generated list is in sorted order:

rangeList
.OrderBy(p => p.FromNumber)
.Select(p => new[] { p.FromNumber, p.ToNumber })
.SelectMany(p => p)
.Aggregate((p, q) => q >= p ? q : int.MaxValue) == int.MaxValue

Problem

I have a list of ranges and I would like to find out if they overlap. I have the following code. Which does not seem to be working. Is there an easier way to do this or a way that works :) Thanks in advance for any advice. ``` public partial class Form1 : Form { public Form1() { InitializeComponent(); } private IList<Range> rangeList; private void Form1_Load(object sender, EventArgs e) { rangeList.Add(new Range{FromNumber = 0, ToNumber = 100}); rangeList.Add(new Range { FromNumber = 101, ToNumber = 200 }); // this range should over lap and throw an exception rangeList.Add(new Range { FromNumber = 199, ToNumber = 300 }); } private bool RangesOverlap() { var bigList = new List<List<int>>(); foreach (var range in this.rangeList) { bigList.Add(new List<int> { range.FromNumber , range.ToNumber }); } IEnumerable<IEnumerable<int>> lists = bigList; return lists .Where(c => c != null && c.Any()) .Aggregate(Enumerable.Intersect) .ToList().Count > 0; } } public class Range { public int FromNumber { get; set; } public int ToNumber { get; set; } } ```

Original source