Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C# Data Types
  • C# Decision Making
  • C# Methods
  • C# Delegates
  • C# Constructors
  • C# Arrays
  • C# ArrayList
  • C# String
  • C# Tuple
  • C# Indexers
  • C# Interface
  • C# Multithreading
  • C# Exception
Open In App
Next Article:
How to sort an Array in C# | Array.Sort() Method Set – 3
Next article icon

How to sort an Array in C# | Array.Sort() Method | Set – 5

Last Updated : 01 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Array.Sort Method is used to sort elements in a one-dimensional array. There are 17 methods in the overload list of this method. Here we will discuss the following methods:
 

Sort<TKey, TValue>(TKey[], TValue[], IComparer<TKey>) Method


This method sorts a pair of array objects based on the keys in the first array using the specified IComparer;T> generic interface. Here in the 2 arrays one contains the keys and the other contains the corresponding items.
 

Syntax: public static void Sort<TKey, TValue> (TKey[] keys, TValue[] items, IComparer comparer); 
Here, TKey is the type of the elements of the key array and TValue the type of the elements of the items array.
Parameters: 
keys: It is the one-dimensional array that contains the keys to sort. 
items: It is the one-dimensional array that contains the items that correspond to the keys in keys. 
comparer: It is the IComparer<T> generic interface implementation to use when comparing elements. 
 


Exceptions:
 

  • ArgumentNullException: If the keys is null.
  • ArgumentException: If the items is not null and the lower bound of keys does not match the lower bound of items or items is not null and the length of keys is greater than the length of items.
  • InvalidOperationException: If comparer is null


Example:
 

csharp
// C# program to demonstrate the use of // Array.Sort<TKey, TValue>(TKey[],  // TValue[], IComparer<TKey>) Method using System; using System.Collections.Generic;  class compare : IComparer<string> {      public int Compare(string x, string y)     {         // Compare x to y         return x.CompareTo(y);     } }  // Driver Class class GFG {      // Main Method     public static void Main()     {         // Initialize two array         String[] arr1 = { "H", "J", "K",                    "L", "I", "N", "M" };          String[] arr2 = { "A", "E", "D",                    "C", "F", "B", "G" };          // Instantiate the IComparer object         compare g = new compare();          // Display original values of the array         Console.WriteLine("The original order of"                     + " elements in the array:");          Display(arr1, arr2);          // Sort the array         // "arr1" is keys array         // "arr2" is items array         // "g" is IComparer<TKey> object         Array.Sort(arr1, arr2, g);          Console.WriteLine("\nAfter Sorting: ");         Display(arr1, arr2);     }      // Display function     public static void Display(String[] arr1,                                String[] arr2)     {         for (int i = 0; i < arr1.Length; i++)         {             Console.WriteLine(arr1[i] + " : " + arr2[i]);         }     } } 

Output: 
The original order of elements in the array: H : A J : E K : D L : C I : F N : B M : G  After Sorting:  H : A I : F J : E K : D L : C M : G N : B

 

Sort<TKey, TValue>(TKey[], TValue[], Int32, Int32) Method

This method is used to sort a range of elements in a pair of array objects based on the keys in the first array. Here in the 2 arrays one contains the keys and the other contains the corresponding items.
 

Syntax: public static void Sort<TKey, TValue> (TKey[] keys, TValue[] items, IComparer comparer, int index, int len); 
Here, TKey is the type of the elements of the key array and TValue is the type of the elements of the items array.
Parameters: 
keys: It is the one-dimensional array that contains the keys to sort. 
items: It is the one-dimensional array that contains the items that correspond to the keys in keys. 
comparer: It is the IComparer<T> generic interface implementation to use when comparing elements. 
index: It is the starting index of the range to sort. 
len: It is the number of elements in the range to sort. 
 


Exceptions:
 

  • ArgumentNullException: If the keys is null.
  • ArgumentOutOfRangeException: If index is less than the lower bound of keys or len is less than zero.
  • ArgumentException: If the items is not null and the lower bound of keys does not match the lower bound of items or items is not null and the len of keys is greater than the length of items or index and len do not specify a valid range in the keysArray or items is not null and index and len do not specify a valid range in the itemsArray.
  • InvalidOperationException: When one or more elements in the keysArray do not implement the IComparable<T> generic interface.


Example:
 

csharp
// C# program to demonstrate the use of // Array.Sort<TKey, TValue>(TKey[], TValue[],  // Int32, Int32) Method using System;  // Driver Class class GFG {      // Main Method     public static void Main()     {         // Initialize two array         String[] arr1 = {"H", "J", "K",                    "L", "I", "M", "N"};          String[] arr2 = {"A", "E", "D",                    "C", "F", "B", "G"};          // Display original values of the array         Console.WriteLine("The original order of"                     + " elements in the array:");          Display(arr1, arr2);          // Sort the array         // "arr1" is keys array         // "arr2" is items array         // start index 1         // range upto index 5         Array.Sort(arr1, arr2, 1, 5);          Console.WriteLine("\nAfter Sorting: ");         Display(arr1, arr2);     }      // Display function     public static void Display(String[] arr1, String[] arr2)     {         for (int i = 0; i < arr1.Length; i++)          {             Console.WriteLine(arr1[i] + " : " + arr2[i]);         }     } } 

Output: 
The original order of elements in the array: H : A J : E K : D L : C I : F M : B N : G  After Sorting:  H : A I : F J : E K : D L : C M : B N : G

 

Sort<TKey, TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) Method

This method is used to sort a range of elements in a pair of array objects based on the keys in the first array using the specified IComparer<T> generic interface. Here in the 2 arrays one contains the keys and the other contains the corresponding items.
 

Syntax: public static void Sort<TKey,TValue> (TKey[] keys, TValue[] items, int index, int len, IComparer<TKey> comparer);
Parameters: 
keys: It is the one-dimensional array that contains the keys to sort. 
items: It is the one-dimensional array that contains the items that correspond to the keys in keys. 
comparer: It is the IComparer<T> generic interface implementation to use when comparing elements. 
index: It is the starting index of the range to sort. 
len: It is the number of elements in the range to sort. 
comparer: It is the IComparer<T> generic interface implementation to use when comparing elements. 
 


Exceptions:
 

  • ArgumentNullException: If the keys is null.
  • ArgumentOutOfRangeException: If the index is less than the lower bound of keys or len is less than zero.
  •  
  • ArgumentException: If items is not null and the lower bound of keys does not match the lower bound of items or items is not null and the len of keys is greater than the length of items or index and len do not specify a valid range in the keysArray or items is not null and index and len do not specify a valid range in the itemsArray or the implementation of comparer caused an error during the sort.
     
  • InvalidOperationException: When one or more elements in the keysArray do not implement the IComparable<T> generic interface.


Example:
 

csharp
// C# program to demonstrate the use of // Array.Sort<TKey, TValue>(TKey[], TValue[], // Int32, Int32, IComparer<TKey>) Method using System; using System.Collections.Generic;  class compare : IComparer<string> {      public int Compare(string x, string y)     {         // Compare x to y         return x.CompareTo(y);     } }  // Driver Class class GFG {      // Main Method     public static void Main()     {         // Initialize two array         String[] arr1 = {"H", "J", "K",                    "L", "I", "M", "N"};          String[] arr2 = {"A", "E", "D",                    "C", "F", "B", "G"};          // Instantiate the IComparer object         compare g = new compare();          // Display original values of the array         Console.WriteLine("The original order of"                     + " elements in the array:");          Display(arr1, arr2);          // Sort the array         // "arr1" is keys array         // "arr2" is items array         // "g" is IComparer<TKey> object         // start index 1         // range upto index 5         Array.Sort(arr1, arr2, 1, 5, g);          Console.WriteLine("\nAfter Sorting: ");         Display(arr1, arr2);     }      // Display function     public static void Display(String[] arr1, String[] arr2)     {         for (int i = 0; i < arr1.Length; i++)          {             Console.WriteLine(arr1[i] + " : " + arr2[i]);         }     } } 

Output: 
The original order of elements in the array: H : A J : E K : D L : C I : F M : B N : G  After Sorting:  H : A I : F J : E K : D L : C M : B N : G

 

Reference: 
 

  • https://docs.microsoft.com/en-us/dotnet/api/system.array.sort?view=netframework-4.7.2


 


Next Article
How to sort an Array in C# | Array.Sort() Method Set – 3

S

SoumikMondal
Improve
Article Tags :
  • Technical Scripter
  • C#
  • CSharp-method
  • CSharp-Arrays

Similar Reads

  • How to sort an Array in C# | Array.Sort() Method Set – 2
    Array.Sort Method is used to sort elements in a one-dimensional array. There are 17 methods in the overload list of this method. Here we will discuss the following methods: Sort(Array, Int32, Int32, IComparer) Method Sort(Array, Array, Int32, Int32, IComparer) Method Sort(Array, Int32, Int32) Method
    9 min read
  • How to Sort an Array in C# | Array.Sort() Method Set - 1
    Array.Sort Method in C# is used to sort elements in a one-dimensional array. There are 17 methods in the overload list of this method as follows: Sort<T>(T[]) MethodSort<T>(T[], IComparer<T>) MethodSort<T>(T[], Int32, Int32) MethodSort<T>(T[], Comparison<T>) Metho
    8 min read
  • How to sort an Array in C# | Array.Sort() Method | Set – 4
    Array.Sort Method is used to sort elements in a one-dimensional array. There are 17 methods in the overload list of this method. Here we will discuss the following methods: Sort(Array) Method This method sorts the elements in an entire one-dimensional array using the IComparable implementation of ea
    5 min read
  • How to sort an Array in C# | Array.Sort() Method Set – 3
    Array.Sort Method is used to sort elements in a one-dimensional array. There are 17 methods in the overload list of this method. Here we will discuss the following methods: Sort(Array, IComparer) Method Sort(Array, Array, IComparer) Method Sort(Array, Array) Method Sort(Array, IComparer) Method This
    6 min read
  • How to sort a list in C# | List.Sort() Method Set -2
    List<T>.Sort() Method is used to sort the elements or a portion of the elements in the List<T> using either the specified or default IComparer<T> implementation or a provided Comparison<T> delegate to compare list elements. There are total 4 methods in the overload list of th
    5 min read
  • How to sort a list in C# | List.Sort() Method Set -1
    List<T>.Sort() Method is used to sort the elements or a portion of the elements in the List<T> using either the specified or default IComparer<T> implementation or a provided Comparison<T> delegate to compare list elements. There are total 4 methods in the overload list of th
    5 min read
  • How to use Array.BinarySearch() Method in C# | Set -2
    Array.BinarySearch() method is used to search a value in a sorted one dimensional array. The binary search algorithm is used by this method. This algorithm searches a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the
    12 min read
  • How to sort an array in a single loop?
    Given an array of size N, the task is to sort this array using a single loop.How the array is sorted usually? There are many ways by which the array can be sorted in ascending order, like: Selection SortBinary SortMerge SortRadix SortInsertion Sort, etc In any of these methods, more than 1 loops is
    12 min read
  • C# | How to convert an ArrayList to Array
    In C#, an array is a group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. The data types of the elements may be any valid data type like char, int, float etc. and the elements are stored in a contiguous location.ArrayList represen
    4 min read
  • C# | How to insert an element in an Array?
    An array is a collection of items stored at contiguous memory locations. In this article, we will see how to insert an element in an array in C#. Let's say we have an array and we want to insert an element at a specific position in this array. Here's how to do it. First get the element to be inserte
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences