How to Convert an Array to a Map in C#

Jan 27, 2024

2 mins read

Published in

Converting an Array to a Map in C#

In C#, transforming an array into a map is a common task, often achieved through the use of a Dictionary. This process allows for efficient key-value pair storage and retrieval. In this blog post, we’ll explore a simple example to illustrate how to convert an array to a map.

Step 1: Understanding Dictionaries

Firstly, let’s grasp the concept of a Dictionary. In C#, it’s a collection of key-value pairs, and it provides methods to add, remove, and access elements based on keys. This makes it an ideal choice for implementing a map.

Step 2: Creating the Array

Let’s start by creating a sample array that we want to convert to a map. For this example, we’ll use an array of integers:

1
int[] myArray = { 1, 2, 3, 4, 5 };

Step 3: Converting Array to Map

Now, let’s write a function that converts our array to a Dictionary. Each element in the array will be a key, and the corresponding value could be any meaningful data. In this case, we’ll use the element itself as the value.

 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
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        int[] myArray = { 1, 2, 3, 4, 5 };

        // Convert array to map
        Dictionary<int, int> myMap = ConvertArrayToMap(myArray);

        // Display the map
        foreach (var kvp in myMap)
        {
            Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
        }
    }

    static Dictionary<int, int> ConvertArrayToMap(int[] array)
    {
        Dictionary<int, int> resultMap = new Dictionary<int, int>();

        foreach (int element in array)
        {
            // Using the element itself as the value for this example
            resultMap[element] = element;
        }

        return resultMap;
    }
}

Step 4: Running the Code

Compile and run the program to see the converted array as a map. The output should display each key-value pair, with the key being the array element and the value being the same in this example.

Conclusion

This simple example demonstrates the basic process of converting an array to a map using a Dictionary in C#. Depending on your use case, you may customize the value associated with each key in the map.

Sharing is caring!