Introduction
Sometimes we need to check the existing records to find out whether the ranges are overlapping/conflicting with each other or not.
Suppose, we have list of ranges, (e.g. range of Min Value and Max Value). Now we need to check whether new range of the Min Value and Max value overlap with the ones. If it is overlapping, then which record gets overlapped?
In this type of case, we can use logic as shown in the below code
Create a class called "Data" as shown in the code below, that can be used to make the list of minValue and maxValue with ID.
- public class Data
- {
- public int id { get; set; }
- public int minValue { get; set; }
- public int maxValue { get; set; }
- }
-
Now, create a data class list as shown below, which will store data. We will consider this as an existing record.
- List<Data> ExistingDataList = new List<Data>();
Add some data and consider it as existing, as shown in the below code.
- ExistingDataList.Add(new Data { id = 1, minValue = 20, maxValue = 30 });
Now, create a new list to store the list of new records.
- List<Data> ConflictedDataList = new List<Data>();
Add data in new list, which we will consider as new records
- ConflictedDataList.Add(new Data { id = 1, minValue = 15, maxValue = 70 });
- ConflictedDataList.Add(new Data { id = 1, minValue = 50, maxValue = 70 });
- ConflictedDataList.Add(new Data { id = 1, minValue = 10, maxValue = 70 });
- ConflictedDataList.Add(new Data { id = 1, minValue = 10, maxValue = 25 });
- ConflictedDataList.Add(new Data { id = 1, minValue = 15, maxValue = 25 });
- ConflictedDataList.Add(new Data { id = 1, minValue = 25, maxValue = 45 });
- ConflictedDataList.Add(new Data { id = 1, minValue = 1, maxValue = 20 });
Add the logic for these two lists and find out which record in the new list overlaps with the existing record and which records don't overlap with the below code
- foreach (var existingData in ConflictedDataList)
- {
- if (ExistingDataList.Count(x =>
- (((x.minValue >= existingData.minValue && x.minValue <= existingData.maxValue) || (x.maxValue >= existingData.minValue && x.maxValue <= existingData.maxValue))
- || ((existingData.minValue >= x.minValue && existingData.minValue <= x.maxValue) || (existingData.maxValue >= x.minValue && existingData.maxValue <= x.maxValue)))
- && x.id == existingData.id) >= 1)
- {
- Console.WriteLine(string.Concat("Conflicted Record : id:", existingData.id," Min Value:",existingData.minValue," Max Value:",existingData.maxValue));
- }
- else
- {
- Console.WriteLine(string.Concat("Not conflicted Record : id:", existingData.id, " Min Value:", existingData.minValue, " Max Value:", existingData.maxValue));
- }
- }
- Console.ReadLine();
Summary
In this blog, we learned how to check the records which overlap.
I hope this code is useful for someone.