Difference Between List and Dictionary in C#

C# Dictionary versus List: Choosing the right data structure when working with data is essential for effective and optimized programming. The Dictionary and List are two frequently utilized data structures. In this tutorial, we'll compare both the Dictionary and List data structures, looking at their traits and analyzing situations where each performs best. You will then be able to choose between the two based on your programming requirements.

Dictionary Data Structure

In the C# programming language, a dictionary is a collection of sets of key-value pairs that provide quick access to values that follow distinctive keys. Utilizing hash tables for implementation ensures effective searching and retrieval.

Example:

using System;


using System.Collections.Generic;


class Program


{


    static void Main()


    {


        // Create a unique dictionary to store student IDs and corresponding names.


        Dictionary<int, string> studentDictionary = new Dictionary<int, string>();


        // Add students to the dictionary.


        studentDictionary.Add(101, "Alice");


        studentDictionary.Add(102, "Bob");


        studentDictionary.Add(103, "Charlie");


        // Attempt to add a duplicate student ID (this will throw an exception).


        try


        {


            studentDictionary.Add(101, "Eve");


        }


        catch (ArgumentException e)


        {


            Console.WriteLine("An error occurred: " + e.Message);


        }


        // Check if a student ID exists in the dictionary.


        int studentIDToFind = 102;


        if (studentDictionary.ContainsKey(studentIDToFind))


        {


            string studentName = studentDictionary[studentIDToFind];


            Console.WriteLine($"Student ID {studentIDToFind} belongs to {studentName}.");


        }


        else


        {


            Console.WriteLine($"Student ID {studentIDToFind} not found.");


        }


    }


}

Output:

Difference Between List and Dictionary in C#

Explanation:

  1. We start by preparing our program with the necessary tools.
  2. We create a special "dictionary" called studentDictionary to keep track of students using their unique IDs.
  3. We add three students to our dictionary, each with their ID and name.
  4. We try to add a student with an ID that already exists, and we're ready to handle any issues that may arise.
  5. We check if a specific student's ID exists in our dictionary.
  6. We print out whether the student was found or not, and if found, we print their name.

List Data Structure

Alternatively, a List in C# serves as an ordered collection of items that enables access according to position or index.

Example:

using System;


using System.Collections.Generic;


class Program


{


    static void Main()


    {


        // Create an empty list to store strings


        List<string> stringList = new List<string>();


        // Add strings to the list


        stringList.Add("Apple");


        stringList.Add("Banana");


        stringList.Add("Cherry");


        // Access and print elements from the list


        Console.WriteLine("List elements:");


        Console.WriteLine(stringList[0]);  // Prints "Apple" (the first element)


        Console.WriteLine(stringList[1]);  // Prints "Banana" (the second element)


        Console.WriteLine(stringList[2]);  // Prints "Cherry" (the third element)


        // Modify an element in the list


        stringList[1] = "Grapes";


        // Remove an element from the list


        stringList.Remove("Cherry");  // Removes the string "Cherry"


        // Check if an element is in the list


        if (stringList.Contains("Banana"))


        {


            Console.WriteLine("Banana is in the list.");


        }


        else


        {


            Console.WriteLine("Banana is not in the list.");


        }


        // Calculate the length of the list


        int listLength = stringList.Count;


        Console.WriteLine("Length of the list: " + listLength);


        // Iterate through the list


        Console.WriteLine("List elements:");


        foreach (string fruit in stringList)


        {


            Console.WriteLine(fruit);


        }


        // Clear the entire list


        stringList.Clear();


        // Check if the list is now empty


        if (stringList.Count == 0)


        {


            Console.WriteLine("The list is empty.");


        }


    }


}

Output:

Difference Between List and Dictionary in C#

Explanation:

  1. We make a list called stringList that is empty in order to store strings.
  2. To include terms (such "Apple," "Banana," and "Cherry") to the list, utilize the Add method.
  3. We may access and print the words in the list by using their locations (or "indices").
  4. We alter a word in the list by indicating its position (index), for instance, changing "Banana" to "Grapes."
  5. By means of the Remove technique, we eliminate a certain word from the list.
  6. Using the Contains command, we determine whether a specific word—like "Banana"—is present in the list.
  7. It is possible to determine how many words are in the list using the Count attribute.
  8. We cycle through every word in the list one at a time using a loop.
  9. Using the Clear technique, we clear the list by removing all the words from it.

Dictionary vs List:

Consider the following aspects while choosing between a Dictionary and a List:

Retrieval of Data

A dictionary is a preferable option if your main requirement is swift data retrieval based on keys. The retrieval of values from dictionaries based on keys has constant-time complexity O(1). Here is an example:

int marks = studentmarks["Alan"]; // Retrieving the value by key

Indexing and sequential access

A List is more appropriate if sequential access or indexing activities are your major concerns. In lists, the elements are always in the correct order, and sequential iteration is quick and easy. As an example, consider the following:

string firstVegetable = vegetable[0]; // Accessing the element by index

Memory Use

When choosing between a Dictionary and a List, take memory usage into account. To handle the hash table and store the key-value pairs, dictionaries need additional memory. Lists, on the flip hand, use less memory because they save the elements without corresponding keys.

Keys or elements that are duplicates

A list is a preferable option if your data has multiple keys or if you need duplicate components. Lists maintain the sequence of insertion and permit duplicate entries. On the other hand, dictionaries ensure unique keys and replace prior values if a duplicate key is introduced.

Complexity Factors

When choosing a data structure, consider the difficulty of the operations. Due to the administration of the hash table, dictionaries may have increased overhead when inserting and deleting words. Lists work well for sequential access but have a linear-time complexity of O(n) for looking at insertion and deletion.

Difference between List and Dictionary in C#:

A List and a Dictionary are both data structures in C# that are used for managing and storing collections of things, although they have different functions and unique qualities:

List:

  • A list is a type of linear collection that keeps items in a particular order.
  • You can store and retrieve things using their index (position) in the List.
  • Zero-based indexing is used to access items (e.g., myList[0]).
  • It is appropriate for situations when you must have an organized collection of things, such as a list of names or numbers.
  • Duplicate list items are those that have the same value listed more than once.
  • Examples of use names in a list are created using new List ();

Dictionary:

  • A dictionary is a collection that contains key-value pairs with a unique key for each value.
  • It enables you to link a value to a certain key, making it simple to access items using their related keys.
  • It is suited for situations when you must carry out quick lookups and value retrieval based on some special identifier (the key).
  • Dictionary keys must be distinct; attempting to add a key that already exists will result in an error.
  • Eg: Dictionary ageLookup = new Dictionary()

In C#, the major use cases and underlying data structures of a List and a Dictionary differ from one another. Use a Dictionary to connect distinct keys with values for quick lookups and retrieval, and use a List to store an ordered collection of objects with potential duplicates.

Examples of List and Dictionary in C#

List example:

using System;


using System.Collections.Generic;


class Program


{


    static void Main()


    {


        // Create a List to store a collection of names.


        List<string> namesList = new List<string>();


        // Add names to the list.


        namesList.Add("Alice");


        namesList.Add("Bob");


        namesList.Add("Charlie");


        // Iterate through the list and print each name.


        Console.WriteLine("Names in the List:");


        foreach (string name in namesList)


        {


            Console.WriteLine(name);


        }


        // Check if a name exists in the list.


        string nameToFind = "Bob";


        if (namesList.Contains(nameToFind))


        {


            Console.WriteLine($"The name {nameToFind} is in the list.");


        }


        else


        {


            Console.WriteLine($"The name {nameToFind} is not in the list.");


        }


    }


}

Output:

Difference Between List and Dictionary in C#

Explanation:

In this example, a list of strings is used to hold a collection of names. Using the Add method, we add names to the list, and then after iterating through the list, we print each name individually. Finally, we use the Contains function to determine whether a specific name is present in the list.

Dictionary example:

using System;


using System.Collections.Generic;


class Program


{


    static void Main()


    {


        // Create a Dictionary to store student IDs and corresponding names.


        Dictionary<int, string> studentDictionary = new Dictionary<int, string>();


        // Add students to the dictionary.


        studentDictionary.Add(101, "Alice");


        studentDictionary.Add(102, "Bob");


        studentDictionary.Add(103, "Charlie");


        // Retrieve and print the name of a student based on their ID.


        int studentIDToFind = 102;


        if (studentDictionary.TryGetValue(studentIDToFind, out string studentName))


        {


            Console.WriteLine($"Student ID {studentIDToFind} belongs to {studentName}.");


        }


        else


        {


            Console.WriteLine($"Student ID {studentIDToFind} not found.");


        }


    }


}

Output:

Difference Between List and Dictionary in C#

Explanation:

In this example, we use a Dictionaryint, string> to store student IDs as keys and corresponding names as values. Using the Add method, we add students to the dictionary. Using the TryGetValue method, which determines whether the key is present in the dictionary and then retrieves the appropriate value, we can access a student's name based on their ID. This enables us to seek student information using their ID quickly.