What is the SortedList class in C#?

CsharpProgrammingServer Side Programming

<p>A sorted list is a combination of an array and a hash table. It contains a list of items that can be accessed using a key or an index. If you access items using an index, it is an ArrayList, and if you access items using a key, it is a Hashtable. The collection of items is always sorted by the key value.</p><p>Let us see an example wherein we added 4 key and value pair for SortedList &minus;</p><h2>Example</h2><pre class="prettyprint notranslate" style="">using System; using System.Collections; namespace Demo { &nbsp; &nbsp;class Program { &nbsp; &nbsp; &nbsp; static void Main(string[] args) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;SortedList s = new SortedList(); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;s.Add(&quot;S1&quot;, &quot;Maths&quot;); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;s.Add(&quot;S2&quot;, &quot;Science&quot;); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;s.Add(&quot;S3&quot;, &quot;English&quot;); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;s.Add(&quot;S4&quot;, &quot;Economics&quot;); &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp;} }</pre><p>Let us now see how to get the keys of a SortedList and display it &minus;</p><h2>Example</h2><pre class="prettyprint notranslate" style="">using System; using System.Collections; namespace Demo { &nbsp; &nbsp;class Program { &nbsp; &nbsp; &nbsp; static void Main(string[] args) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;SortedList sl = new SortedList(); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;sl.Add(&quot;ST0&quot;, &quot;One&quot;); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;sl.Add(&quot;ST1&quot;, &quot;Two&quot;); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;sl.Add(&quot;ST2&quot;, &quot;Three&quot;); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;sl.Add(&quot;ST3&quot;, &quot;Four&quot;); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;sl.Add(&quot;ST4&quot;, &quot;Five&quot;); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;sl.Add(&quot;ST5&quot;, &quot;Six&quot;); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;sl.Add(&quot;ST6&quot;, &quot;Seven&quot;); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;ICollection key = sl.Keys; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;foreach (string k in key) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine(k); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp;} }</pre>
raja
Updated on 21-Jun-2020 14:23:11

Advertisements