In C#, SortedSet is a collection of objects in sorted order. It is of the generic type collection and defined under System.Collections.Generic namespace. It also provides many mathematical set operations, such as intersection, union, and difference. It is a dynamic collection means the size of the SortedSet is automatically increased when the new elements are added.
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | private void button1_Click(object sender, EventArgs e) { var sortedSet=new SortedSet<string>(); sortedSet.Add("C#"); sortedSet.Add("Python"); sortedSet.Add("C++"); sortedSet.Add("Java"); sortedSet.Add("Visual Basic"); sortedSet.Add("C"); foreach (var item in sortedSet) { listBox1.Items.Add(item); } } |
Example 2:
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | static public void Main() { // Creating SortedSet // Using SortedSet class SortedSet<int> my_Set1 = new SortedSet<int>(); // Add the elements in SortedSet // Using Add method my_Set1.Add(101); my_Set1.Add(1001); my_Set1.Add(10001); my_Set1.Add(100001); Console.WriteLine("Elements of my_Set1:"); // Accessing elements of SortedSet // Using foreach loop foreach(var val in my_Set1) { Console.WriteLine(val); } // Creating another SortedSet // using collection initializer // to initialize SortedSet SortedSet<int> my_Set2 = new SortedSet<int>() { 202,2002,20002,200002}; // Display elements of my_Set2 Console.WriteLine("Elements of my_Set2:"); foreach(var value in my_Set2) { Console.WriteLine(value); } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 | Elements of my_Set1: 101 1001 10001 100001 Elements of my_Set2: 202 2002 20002 200002 |