Table of Contents:

    1. What is the .NET Framework?
    2. Data Structures in .NET
    3. Tuple in .NET
    4. LinkedList in .NET
    5. Key-Value Pair in .NET

What is the .NET Framework?

The famous .NET is a software framework that Microsoft developed. This framework runs on Windows and provides cross-language compatibility. It has a vast class library known as Framework Class Library (FCL) that helps in language interoperability. The developers use Common Language Runtime (CLR) to execute programs written in the .Net framework. CLR is responsible for providing security, memory management, and exception handling services.

Data Structures in .NET

Similar to other programming languages, the .NET framework also supports various types of data structures. The .NET framework uses the language C# for programming purposes. Microsoft developed the language C#, and it is quite helpful in developing web, desktop, and mobile applications and developing various kinds of games, and much more. Some of the primary data structures used in .NET are the following:

  • ArrayList
  • List
  • HashTable
  • Dictionary
  • SortedList
  • SortedDictionary
  • Key-Value Pair
  • Linked List
  • Tuple

The use of these data structures in .NET is quite complicated. The reason is that most of the data structures supported by .NET are somewhat similar, which raises confusion about the proper usage of these in certain situations. Below is an explanation of these data structures.

Collections in C#

There are some special classes in C#, which are often known as collection classes. The primary purpose of these collection classes is to store and retrieve the required data for the program. These collection classes help support most of the operations used in .NET, such as stacks, queues, lists, hash tables, and many more.

ArrayList in .NET

The users can consider the ArrayList as a non-generic combination of objects in C#. The size of this combination can increase dynamically. The only difference between Array and ArrayList in C# is the ability to increase its size dynamically. ArrayList supports adding unknown data without knowing its type and size. The namespace used for creating ArrayList is known as the Systems. Collections. Following is the example of using ArrayList in C#.

ArrayList Example in C#

The users can create an instance for ArrayList using the new keyword. Moreover, they can then use the Add ( ) function to add new elements to this newly created list along with multiple null and duplicate values. Following is a sample code for using ArrayList collection:

Assigning values ( Method 1 )

using namespace System.Collections;
ArrayList arr1 = new ArrayList ( ) ;            //first method
var arr1 = new ArrayList ( ) ;                     //second method
 //adding various types of new elements
arr1.Add ( 50 ) ;
arr1.Add ( “Name” ) ;
arr1.Add ( true ) ;
arr1.Add ( 6.7 ) ;
arr1.Add ( null ) ;
arr1.Add ( “ ” ) ;

Assigning values ( Method 2 )

Another way to add elements in the ArrayList is to utilize object initializer syntax. Object initializers help to assign values to the fields at the time of object creation. This method saves the effort of invoking a constructor for assigning values. Following is an example of adding elements to ArrayList using an object initializer:

var arr1 = new ArrayList ( )
                        {
                               50, “Name”, true, 6.7, null, “ ”
                        } ;

Adding an ArrayList

The ArrayList data structure can add various other data structures to it. For example, it can add the whole array, hash table, sorted list, array list, bit array, Queue, and even stack in it. For this purpose, the developers use the AddRange ( )  function in the. NET framework, which provides the desired results. An example of such code is the following:


var arr2 = new ArrayList ( ) ;
 var arr1 = new ArrayList ( )
                        {
                               50, “Name”, true, 6.7, null, “ ”
                        } ;
Int [ ] arr3 = { 2, 4, 6, 8 } ;
Queue q1 = new Queue ( ) ;
q1.Enqueue ( “ One ” ) ;
q1.Enqueue ( “ Two ” ) ;
arr2.AddRange ( arr1 ) ;
arr2.AddRange ( arr3 ) ;
arr2.AddRange ( q1 ) ;

Insertion in ArrayList

An ArrayList allows the insertion of elements at any specified index. For this purpose, the developers can call the Insert ( ) function. This function takes the specific index as its first argument and specified value as its second argument and successfully inserts that element in the list. Following is an example of the Insert ( ) function:

//using already declared arr1 in this example
arr1.Insert ( 2, 678 );
foreach ( var v in arr1 )
      Console.WriteLine ( v ) ;

Here, the sample code uses the foreach keyword to iterate through the entire list, and WriteLine prints the array elements on the console for display.

Deletion from ArrayList

Developers can use various methods of deletion from an ArrayList using functions like Remove ( ), RemoveAt ( ), and RemoveRange ( ). The Remove ( ) function deletes the first occurrence of null. The RemoveAt ( ) function takes the index of an element and removes it. Finally, the RemoveRange ( ) function deletes the elements from a range specified as the arguments. A simple example of such functions is following:

var arr1 = new ArrayList ( )
                        {
                               50, “Name”, true, 6.7, null, “ ”
                        } ;
arr1.Remove ( null ) ;
arr1.RemoveAt ( 3 ) ;
arr1.RemoveRange ( 1, 3 ) ;

Tuple in .NET

In .NET, the symbol < T > describes the tuple. The tuple is a data structure that contains a sequence of elements having different data types. In the .NET framework, the tuple is a data structure providing an easier method for representing a single set of data. Therefore, the .NET developers introduced the tuple class in the .NET framework 4.0. Furthermore, the .NET framework supports the tuples having 7 elements directly. In the tuple structure, the 8th element is often called TRest. Since the .NET framework does not support having more than seven elements in it, the 8th element, TRest, can create nesting tuple objects. Moreover, tuple proves helpful in holding objects having different properties. The tuple representation is the following:

Tuple < T1, T2, T3, T4, T5, T6, T7, TRest >

Tuple Example in C#

Below is an explanation of an example of a tuple having different data types. It is an example of a student record. The user provides the specific data types and their values to the tuple, and the new keyword creates a tuple having the following properties:

Tuple < int, string, string > student = new Tuple < int, string, string > ( 1, “John”, “Doe” ) ;

Instead of specifying the data type of every element of the tuple, there is an easier way to do it. A static class in C#, namely tuple, provides an instance of the tuple without manually specifying each element’s data type. Following is an example of such a static class:

var student = Tuple.Create ( 1, "John", "Doe") ; 

Access to Tuple Elements

After declaring the tuple elements, the users can access them using the Item< elementNumber > method. Specifying the relevant number with Item returns the specific element assigned at that position. Following is a simple example of accessing tuple elements:

var student = Tuple.Create ( 1, "John", "Doe") ;
student.Item1 ;
student.Item2 ;
student.Item3 ; 

Nested Tuple

As explained earlier, the users need to use the 8th element of a tuple as the nested tuple object when needed. Although the nested tuple can be created anywhere within a tuple, the developers usually create it at the 8th element for having an easier approach to its elements. To access the nested tuple, the developers use the Rest property in the .NET along with the Item method. Following is an example to access nested tuple:

var students =Tuple.Create ( 1, "John", "Doe", 2, "Abc", "Xyz", 3, Tuple.Create (  4, "Hello", "World")) ;

students.Item1 ;
students.Item2 ;
students.Item3 ;
students.Item4 ;
students.Item5 ;
students.Item6 ;
students.Item7 ;
students.Rest.Item1 ;
students.Rest.Item1.Item1 ;
students.Rest.Item1.Item2 ;
students.Rest.Item1.Item3 ;

Moreover, a tuple can be used as a parameter of a method when needed. Similarly, the framework allows using tuple as a return type from a function.

Advantages of Using the Tuple

Tuple provides various advantages while programming for a complicated task. Following are some of the benefits of using tuples:

  • It helps in returning multiple values from a function without using ref or out statements.
  • It helps in passing multiple values to a method by being a parameter for the function.
  • It does not require creating an extra separate class to store the database record of values. Merely using a tuple can hold the values for you.

ValueTuple in .NET

Simple tuple in the .NET framework had some limitations. Some of the Tuple limitations are following:

  • It was a reference type and not a value type.
  • It was allocated on the heap and produced CPU-intensive operations.
  • Adding nested tuples after 7 elements raised many ambiguities.

The .NET framework introduced the ValueTuple to overcome the above limitations found in the Tuple structure. However, this is only available for the .NET Framework 4.7 or higher versions. It is a value-type representation of the original tuple.

ValueTuple Examples in C#

The valueTuple has more than one method to be created and initialized. One method is to use parentheses and specify values in them. On the other hand, the users can initialize it by using data types of each element separately. Moreover, it also allows users to use only parentheses for declaring and assigning values to the elements. Following are all of the example codes for these methods:

var student = ( 1, “John”, “Doe” ) ;  //method 1
ValueTuple < int, string, string > student = ( 1, “John”, “Doe” ) ;  // method 2
( int, string, string ) student = ( 1, “John”, “Doe” ) ;   //method 3

ValueTuple allows including more than eight values as its elements. Another feature of ValueTuple is that it includes named members as its elements. Therefore, instead of having confusion regarding Item1 and Item2 when accessing the tuple elements, developers can name them to access them. Following is an example of such assignments:

var counting = ( 1, 2, 3, 4, 5, 6, 7,8 9, 10 ) ;
(int Id, string fName, string lName ) student = ( 1, “John”, “Doe” ) ; 
student.Id ;
student.fName ;
student.lName ;

LinkedList in .NET

In a programming language, the LinkedList represents a linear type of data structure. It is called a linked list due to the link of every element in the list with each other through pointers’ proper use. Each node in the list consists of a data field and a link to the next node. Moreover, in C#, LinkedList lies under the generic type of collection. The users can find its definition in System.Collections.Generic namespace. As the name generic suggests, it is not specific for a particular type of data. C# contains a doubly-linked list, which means that each node has two pointers. One pointer is to link with the next node, and the other is to link with the previous one. The size of this list increases dynamically, and the operations like insertion and deletion are way faster.

Benefits of using LinkedList in C#

Despite having various data structures to store and revive data, LinkedList proves a better option in certain situations. With all its features and functionalities, LinkedList provides some of the real benefits over other data structures. Following are a few advantages of using LinkedList:

  • Since the LinkedList algorithms allocate memory dynamically, it is easier to use when the data grows or gets removed during the program. Moreover, there is no need to define memory size at first, resulting in the effective utilization of program memory.
  • It provides a more straightforward implementation of insertion and deletion.
  • It supports the implementation of stacks and queues along with it.
  • LinkedList provides faster access time and reduces the memory overhead during the process of expansion in constant time.
  • Doubly LinkedList provides the option of backtracking also.
  • The LinkedList class consists of ICollection <T>, IEnumerables <T>, IReadOnlyCollection <T>, IDeserializationCallback and many other interfaces.
  • It does not allow performing operations such as chaining, splitting, cycles, and other features to make a list inconsistent.

LinkedList Example in C#

There are three types of constructors available for creating a LinkedList class in C#. One provides a simple method to initialize an instance of LinkedList having an empty class by using the LinkedList ( ) function. The second method is to create an instance with copied elements from a specific IEnumerable class and cater to them all. This method is to use the LinkedList ( IEnumerable ) function. Finally, the third method is to create an instance using the LinkedList ( SerializationInfo, StreamingContext ) function, which provides serialization having specified info and context. Following is an example of LinkedList in C#:

using System;
using System.Collections.Generic ;
public class LinkedList_Example {
           public static void Main( )
              {
                      LinkedList < String > example_list = new LinkedList < String > ( ) ;
                      example_list.AddFirst ( “ John ” ) ;
                      foreach ( string i in example_list )
                      {
                             Console.WriteLine ( i ) ;
                      }
                }
 }

Addition in LinkedList

The addition operation in LinkedList is relatively more straightforward than other data structures. It provides 4 different methods of additions in the list. The AddAfter( ) method provides an option to add a new node after the existing node or value in the list. Similarly, the AddBefore ( ) method adds the node or value before the existing node in the list. Moreover, the AddFirst ( ) method performs the addition operation at the start of the list. On the other hand, the AddLast ( ) operation performs the addition at the end of the list. Following is an example of adding to LinkedList:

using System ;
using System.Text ;
using System.Collections.Generic ;
public class LinkedList_Example {
           public static void Main( )
              {
                 String [ ] words = { “my”, “name”, “is”} ;
                 LinkedList <string> sentence = new LinkedList <string> (words) ;
                 Display ( sentence, “Linked List contains:” ) ;
                 sentence.AddFirst ( “Hi”) ;
                 sentence.AddLast (“John”) ;
                  foreach ( string i in sentence )
                      {
                             Console.WriteLine ( i ) ;
                      }
               }
 }

Deletion from LinkedList

Similar to the insertion operation, deletion operation also has various methods in LinkedList. The LinkedList <T> class allows deletion from the list using five different methods. The Clear ( ) function helps to make a list empty by removing all nodes from it. The Remove ( Node) function takes a specific node as its parameter and removes it. The Remove (T) function helps remove the first occurrence of a particular value provided as its argument. However, the RemoveFirst ( ) function deletes the list’s starting node, and the RemoveLast ( ) function deletes the ending node of the list. An example of deletion from the LinkedList is following:

using System ;
using System.Text ;
using System.Collections.Generic ;
public class LinkedList_Example {
           public static void Main( )
              {
                 String [ ] words = { “my”, “name”, “is”, “John”} ;
                 LinkedList <string> sentence = new LinkedList <string> (words) ;
                 foreach ( string i in sentence )
                      {
                             Console.WriteLine ( I ) ;
                      }
                sentence.Remove ( sentence.First ) ;
                 foreach ( string i in sentence )
                      {
                             Console.WriteLine ( i ) ;
                      }
                  sentence.RemoveFirst ( ) ;
                    foreach ( string i in sentence )
                      {
                             Console.WriteLine ( i ) ;
                      }
                  Sentence.RemoveLast ( ) ;
                    foreach ( string i in sentence )
                      {
                             Console.WriteLine ( i ) ;
                      }
                     Sentence.Clear ( ) ;
                    foreach ( string i in sentence )
                      {
                             Console.WriteLine ( i ) ;
                      }
              }
}

Key-Value Pair in .NET

In the .NET framework, the developers use the key-value pair class to store a pair of values in a single list with C#. Usually, a key-value pair has two interlinked values so that the value is accessed using the key linked with it. The purpose of these in numerous data structures is to help with faster access to values. The key here is a constant which the developers utilize to define a data set. However, the value is a variable that belongs to a specific data set. In C#, the KeyValuePair class comes under the System.Collections.Generic namespace.

KeyValuePair Example in C#

A key-value pair can store information about a specific set of data. The developers can call Add ( ) function to add new elements to the list after creation. In making the function call, they pass a key pair and its value as the function’s argument. Following is a simple example of creating a list having KeyValuePairs in C#:

using System ;
using System.Collections.Generic ;
public class LinkedList_Example {
           public static void Main( )
              {
                   var example_list = new List <KeyValuePair < string, int > > ( ) ;
                   example_list.Add ( new KeyValuePAir < string, int > (“Mobile”, 15 ) ) ;
                   example_list.Add ( new KeyValuePAir < string, int > (“Laptop”, 20 ) ) ;
                   foreach ( string i in example_list )
                      {
                             Console.WriteLine ( i ) ;
                      }
              }
}

Uses of Key-value Pairs

A key-value pair contains a set of two data items that are linked and have a unique identifier for a data set as the key and a pointer to that data, which specifies it called the value. Moreover, the developers often use the key-value pairs in dictionaries, lookup tables, hash tables, and configuration files to ease the search of a specific value.