In C#, SortedList is a collection of key-value pairs sorted according to keys. By default, this collection sorts ascendingly It is of both generic and non-generic type of collection. The generic SortedList is defined in the System.Collections.Generic namespace whereas non-generic SortedList is defined under System.Collections namespace, here we will discuss the non-generic type SortedList.
- Elements are sorted by key in ascending order.
- The keys are defined uniquely but we can store duplicate values.
- Offer to store data in keys and value pairs.
- No need to define the size we can add elements without giving the size like arrays.
Example:
C#
// Creating and adding key, values to the sorted list
using System;
using System.Collections.Generic;
class Geeks
{
public static void Main()
{
// Creating a SortedList
SortedList<int, string> sl = new SortedList<int, string>();
// Adding key-value pairs
sl.Add(3, "Three");
sl.Add(1, "One");
sl.Add(2, "Two");
// Displaying elements in sorted by key
foreach (var item in sl)
{
Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
}
}
}
OutputKey: 1, Value: One
Key: 2, Value: Two
Key: 3, Value: Three
Steps to Create SortedList
We can use the SortedList Class which provides different ways to create a Sorted list. Here, we use the SortedList Class constructor to create a sorted list. Which is used to create an instance of the SortedList class that is empty by default and sorted according to the IComparable interface implemented by each key added to the SortedList object.
Step 1: Include System.Collections namespace
using System.Collections;
Step 2: Create a SortedList using the SortedList class
SortedList list_name = new SortedList();
Performing Different Operations on SortedList
1. Adding Elements
For adding elements list, The List<T> class provides two different methods which are:
- Add() : This method is used to add an object to the SortedList<T>.
- Collection Initializer: We can use Collection Initializer to add elements in SortedList<TKey, TValue>.
Syntax:
// Add element using Add method
list.Add(key, value);
// Adding elements using the
// Collection initializers
SortedList<Tkey, Tvalue> mySortedList = new SortedList<int, string>()
{
{ Key, Value },
{ Key, Value },
};
Example: Creating sortedList using different ways.
C#
// C# program to illustrate how
// to create a sortedlist
using System;
using System.Collections;
class Geeks {
static public void Main() {
// Creating a sortedlist
// Using SortedList class
SortedList sl = new SortedList();
// Adding key-value pairs in
// SortedList using Add() method
sl.Add(1.02, "This");
sl.Add(1.07, "Is");
sl.Add(1.04, "SortedList");
foreach(DictionaryEntry pair in sl)
{
Console.WriteLine("{0} and {1}",
pair.Key, pair.Value);
}
Console.WriteLine();
// Creating another SortedList
// using Object Initializer Syntax
// to initialize sortedlist
SortedList my_slist2 = new SortedList() {
{ "b.09", 234 },
{ "b.11", 395 },
{ "b.01", 405 },
{ "b.67", 100 }};
foreach(DictionaryEntry pair in my_slist2)
{
Console.WriteLine("{0} and {1}",
pair.Key, pair.Value);
}
}
}
Output1.02 and This
1.04 and SortedList
1.07 and Is
b.01 and 405
b.09 and 234
b.11 and 395
b.67 and 100
2. Accessing SortedList
There are three different ways to access the elements of the SortedList as it is stored in the Key-Value pair we can get the Key and value separately.
Using for Loop: We can use Loop to iterate through the list and access key-value pairs we can use List.GetKey() method to access the key and similarly from the key we can access the value by using List.GetByIndex(key).
Syntax:
for (int i = 0; i < sList.Count; i++)
{
Console.WriteLine("{0} and {1}",
sList.GetKey(i), // Acessing keys
sLIst.GetByIndex(i)); // Acessing values
}
Using ForEach Loop: We can use a foreach loop to access the key-value pairs of the SortedList. In the foreach loop, we can use a dictionary. It is mostly used to access the list stored in key-value pairs.
Syntax:
foreach(DictionaryEntry pair in my_slist1)
{
Console.WriteLine("{0} and {1}",
pair.Key, pair.Value);
}
Using Indexers: We can access the individual value of the SortedList by using the index. We need to pass the key or index as a parameter to find the respective value. It is similar to how we access the array.
Syntax:
Console.WriteLine("Value is:{0}", my_slist1[1.04]);
string x = (string)my_slist[1.02];
Console.WriteLine(x);
Note: If the specified key is not available, then the compiler will throw an error.
Example: Demonstration of accessing SortedList in different ways.
C#
// Creating a SortedList and
// accessing its elements
using System;
using System.Collections;
class Geeks
{
static void Main()
{
SortedList sl = new SortedList {
{ 1, "Geek1" }, { 2, "Geek2" }, { 3, "Geek3" }
};
// Using for loop
Console.WriteLine("Access using for loop");
for (int i = 0; i < sl.Count; i++)
Console.WriteLine($"{sl.GetKey(i)}: {sl.GetByIndex(i)}");
// Using foreach loop
Console.WriteLine("Access using foreach loop");
foreach (DictionaryEntry entry in sl)
Console.WriteLine($"{entry.Key}: {entry.Value}");
// Using indexer
Console.WriteLine("Access using indexer");
Console.WriteLine($"Key 2: {sl[2]}" );
}
}
OutputAccess using for loop
1: Geek1
2: Geek2
3: Geek3
Access using foreach loop
1: Geek1
2: Geek2
3: Geek3
Access using indexer
Key 2: Geek2
3. Removing Elements
- Clear: This method is used to remove all elements from a SortedList object.
- Remove: This method is used to remove the element with the specified key from a SortedList object.
- RemoveAt: This method is used to remove the element at the specified index of a SortedList object.
Example:
C#
// Removing key-value pairs from
// the sortedlist
using System;
using System.Collections;
class Geeks
{
static public void Main()
{
// Creating a sortedlist
// Using SortedList class
SortedList sl = new SortedList();
// Adding key/value pairs in SortedList
// Using Add() method
sl.Add(1, "one");
sl.Add(2, "two");
sl.Add(3, "three");
foreach(DictionaryEntry pair in sl)
{
Console.WriteLine("{0} and {1}",
pair.Key, pair.Value);
}
Console.WriteLine();
// Remove value having 1.07 key
// Using Remove() method
sl.Remove(1);
// After Remove() method
foreach(DictionaryEntry pair in sl)
{
Console.WriteLine("{0} and {1}",
pair.Key, pair.Value);
}
Console.WriteLine();
// Remove element at index 2
// Using RemoveAt() method
sl.RemoveAt(1);
// After RemoveAt() method
foreach(DictionaryEntry pair in sl)
{
Console.WriteLine("{0} and {1}",
pair.Key, pair.Value);
}
Console.WriteLine();
// Remove all key/value pairs
// Using Clear method
sl.Clear();
Console.WriteLine("Total pairs"+
" present in sorted list is: {0}", sl.Count);
}
}
Output1 and one
2 and two
3 and three
2 and two
3 and three
2 and two
Total pairs present in sorted list is: 0
4. Check Element
We can check the element of the SortedList by using the methods available below it returns value in boolean if the the element present returns true either false.
- Contains: This method is used to check whether a SortedList object contains a specific.
- ContainsKey: This method is used to check whether a SortedList object contains a specific key.
- ContainsValue: This method is used to check whether a SortedList object contains a specific value.
Example:
C#
// Check the given key or value
// present in the sortedlist or not
using System;
using System.Collections;
class Geeks
{
static public void Main()
{
// Creating a sortedlist
// Using SortedList class
SortedList sl = new SortedList();
// Adding key-value pairs in
// SortedList using Add() method
sl.Add(1, "one");
sl.Add(2, "two");
sl.Add(3, "three");
// Using Contains() method to check
// the specified key is present or not
if (sl.Contains(1))
Console.WriteLine("Key is found...!!");
else
Console.WriteLine("Key is not found...!!");
// Using ContainsKey() method to check
// the specified key is present or not
if (sl.ContainsKey(2))
Console.WriteLine("Key is found...!!");
else
Console.WriteLine("Key is not found...!!");
// Using ContainsValue() method to check
// the specified value is present or not
if (sl.ContainsValue("one"))
Console.WriteLine("Value is found...!!");
else
Console.WriteLine("Value is not found...!!");
}
}
OutputKey is found...!!
Key is found...!!
Value is found...!!
Important Points
- The SortedList class implements the IEnumerable, ICollection, IDictionary and ICloneable interfaces.
- In SortedList, an element can be accessed by its key or by its index.
- A SortedList object internally maintains two arrays to store the elements of the list, i.e., one array for the keys and another for the associated values.
- Here, a key cannot be null, but a value can be.
- The capacity of a SortedList object is the number of key-value pairs it can hold.
- In SortedList, duplicate keys are not allowed.
- In SortedList, we can store values of the same type and of the different types due to the non-generic collection. If you use a generic SortedList in your program, then the type of the values must be the same.
- SortedList only allows keys of the same type, mixing types will cause a compiler exception.
- We can also cast key/value pair of SortedList into DictionaryEntry.
Similar Reads
Introduction
C# TutorialC# (pronounced "C-sharp") is a modern, versatile, object-oriented programming language developed by Microsoft in 2000 that runs on the .NET Framework. Whether you're creating Windows applications, diving into Unity game development, or working on enterprise solutions, C# is one of the top choices fo
4 min read
Introduction to .NET FrameworkThe .NET Framework is a software development framework developed by Microsoft that provides a runtime environment and a set of libraries and tools for building and running applications on Windows operating systems. The .NET framework is primarily used on Windows, while .NET Core (which evolved into
6 min read
C# .NET Framework (Basic Architecture and Component Stack)C# (C-Sharp) is a modern, object-oriented programming language developed by Microsoft in 2000. It is a part of the .NET ecosystem and is widely used for building desktop, web, mobile, cloud, and enterprise applications. This is originally tied to the .NET Framework, C# has evolved to be the primary
6 min read
C# Hello WorldThe Hello World Program is the most basic program when we dive into a new programming language. This simply prints "Hello World!" on the console. In C#, a basic program consists of the following:A Namespace DeclarationClass Declaration & DefinitionClass Members(like variables, methods, etc.)Main
4 min read
Common Language Runtime (CLR) in C#The Common Language Runtime (CLR) is a component of the Microsoft .NET Framework that manages the execution of .NET applications. It is responsible for loading and executing the code written in various .NET programming languages, including C#, VB.NET, F#, and others.When a C# program is compiled, th
4 min read
Fundamentals
C# IdentifiersIn programming languages, identifiers are used for identification purposes. Or in other words, identifiers are the user-defined name of the program components. In C#, an identifier can be a class name, method name, variable name, or label. Example: public class GFG { static public void Main () { int
2 min read
C# Data TypesData types specify the type of data that a valid C# variable can hold. C# is a strongly typed programming language because in C# each type of data (such as integer, character, float, and so forth) is predefined as part of the programming language and all constants or variables defined for a given pr
7 min read
C# VariablesIn C#, variables are containers used to store data values during program execution. So basically, a Variable is a placeholder of the information which can be changed at runtime. And variables allows to Retrieve and Manipulate the stored information. In Brief Defination: When a user enters a new valu
4 min read
C# LiteralsIn C#, a literal is a fixed value used in a program. These values are directly written into the code and can be used by variables. A literal can be an integer, floating-point number, string, character, boolean, or even null. Example:// Here 100 is a constant/literal.int x = 100; Types of Literals in
5 min read
C# OperatorsIn C#, Operators are special types of symbols which perform operations on variables or values. It is a fundamental part of language which plays an important role in performing different mathematical operations. It takes one or more operands and performs operations to produce a result.Types of Operat
7 min read
C# KeywordsKeywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to be used as variable names or objects. Doing this will result in a compile-time error.Example:C#// C# Program to illustrate the
5 min read
Control Statements
C# Decision Making (if, if-else, if-else-if ladder, nested if, switch, nested switch)Decision Making in programming is similar to decision making in real life. In programming too, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of program based on certain conditions. These
5 min read
C# Switch StatementIn C#, Switch statement is a multiway branch statement. It provides an efficient way to transfer the execution to different parts of a code based on the value of the expression. The switch expression is of integer type such as int, char, byte, or short, or of an enumeration type, or of string type.
4 min read
C# LoopsLooping in a programming language is a way to execute a statement or a set of statements multiple times, depending on the result of the condition to be evaluated to execute statements. The result condition should be true to execute statements within loops.Types of Loops in C#Loops are mainly divided
4 min read
C# Jump Statements (Break, Continue, Goto, Return and Throw)In C#, Jump statements are used to transfer control from one point to another point in the program due to some specified code while executing the program. In, this article, we will learn to different jump statements available to work in C#.Types of Jump StatementsThere are mainly five keywords in th
4 min read
OOP Concepts
Methods
Arrays
C# ArraysAn 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. Length of the array spe
8 min read
C# Jagged ArraysA jagged array is an array of arrays, where each element in the main array can have a different length. In simpler terms, a jagged array is an array whose elements are themselves arrays. These inner arrays can have different lengths. Can also be mixed with multidimensional arrays. The number of rows
4 min read
C# Array ClassArray class in C# is part of the System namespace and provides methods for creating, searching, and sorting arrays. The Array class is not part of the System.Collections namespace, but it is still considered as a collection because it is based on the IList interface. The Array class is the base clas
7 min read
How to Sort an Array in C# | Array.Sort() Method Set - 1Array.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>) Method
8 min read
How to find the rank of an array in C#Array.Rank Property is used to get the rank of the Array. Rank is the number of dimensions of an array. For example, 1-D array returns 1, a 2-D array returns 2, and so on. Syntax: public int Rank { get; } Property Value: It returns the rank (number of dimensions) of the Array of type System.Int32. B
2 min read
ArrayList
String
Tuple
Indexers