我有一个范围列表,我想知道它们是否重叠.
我有以下代码.哪个似乎没有用.有没有更简单的方法来做到这一点或工作的方式:)
提前感谢任何建议.
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; } }
解决方法
首先合并数字,然后检查生成的列表是按排序顺序:
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