Check if the given ranges are equal or not in C#


As programmers, we often encounter situations where we need to compare two ranges in a programming language like C#. Whether we're working on complex algorithms or simple programs, checking if two ranges are equal can be a critical task. This article will discuss the process and methods to compare two given ranges in C#, providing a straightforward solution to this common problem.

Understanding Ranges in C#

Before we proceed to the solution, it's vital to have a firm understanding of what ranges are in the C# programming language. Introduced in C# 8.0, ranges are a new feature that provides a syntax for working with subsets of different types of data like arrays, strings, and spans.

A range can be defined using two dots ('..'). For example, an expression like '1..4' represents a range that includes 1, 2, and 3.

Method to Check if Given Ranges are Equal in C#

The simplest way to check if two ranges are equal is to convert them into arrays or lists and then compare those collections. We will define a function 'AreRangesEqual' which will do just this −

Example

using System;

public class Program {
   public static void Main() {
      int[] range1 = { 1, 2, 3 };
      int[] range2 = { 1, 2, 3 };
      
      bool areEqual = AreRangesEqual(range1, range2);
      Console.WriteLine($"Are the ranges equal? {areEqual}");
   }

   public static bool AreRangesEqual(int[] range1, int[] range2) {
      // Check if both ranges have the same length.
      if (range1.Length != range2.Length) {
         return false;
      }

      // Sort both ranges.
      Array.Sort(range1);
      Array.Sort(range2);

      // Compare the sorted ranges.
      for (int i = 0; i < range1.Length; i++) {
         if (range1[i] != range2[i]) {
            return false;
         }
      }

      return true;
   }
}

In the above function, we first check if both ranges have the same length. If they do not, we can immediately return false. We then sort both ranges and compare them. If any corresponding pair of elements are not equal, we return false. If none of the pairs are unequal, we return true.

Output

Are the ranges equal? True

Conclusion

Understanding and comparing ranges in C# is an essential skill in modern programming with this language. The method we've discussed provides a simple, yet effective, way of checking if given ranges are equal or not. However, keep in mind that there may be more sophisticated methods for specific situations or types of data.

Updated on: 24-Jul-2023

53 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements