c sharp

How to Use KeyValuePair for Storing Pairs in C#

Structs, commonly known as structures, are a value types that are used to encapsulate a small group of related variables. Structs are mainly comprised of data members that are known as fields, methods, properties, indexers, operators, events, and nested types. Think of a struct like some sort of a class but with a different functionality.

One of the most common structs in C# is the KeyValuePair struct. This struct allows us to store a pair of elements in the form of key-value pair. If you need to work with dictionaries in C#, this is the feature that you need.

Hence, in this tutorial, we will learn everything you need to know to start working with and using the KeyValuePair struct.

The Basics

The following shows the definition for the KeyValuePair struct:

public readonly struct KeyValuePair<TKey,TValue>

The type accepts the TKey and TValue parameters which denote the type of the key and the type of the value, respectively.

We can use these parameters to create a basic key-value pair as shown in the following example code:

using System;
using System.Collections.Generic;
class Program
{
    static void Main()
    {
        KeyValuePair<int, string> pair = new KeyValuePair<int, string>(3306, "MySQL");
        Console.WriteLine($"Key: {pair.Key}, Value: {pair.Value}");
    }
}

In the given example, we start by importing the required namespaces. In this case, we import the System and System.Collections.Generic which contain the definition to the KeyValuePair struct.

Next, we create a KeyValuepair of type <int, string> where the int represents the type of the key and the string is the value type.

Finally, we access the key and values and print them to the console.

Output:

Key: 3306, Value: MySQL

Create a List of KeyValuePairs

C# allows us to create a collection of KeyValuePair objects using collections such as array or lists.

Take a look at the following code sample:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<KeyValuePair<int, string>> pairs = new List<KeyValuePair<int, string>>
        {
            new KeyValuePair<int, string>(3306, "MysSQL"),
            new KeyValuePair<int, string>(9200, "Elasticsearch"),
            new KeyValuePair<int, string>(6379, "Redis")
        };

        foreach (var pair in pairs)
        {
            Console.WriteLine($"Port: {pair.Key}, Database: {pair.Value}");
        }
    }
}

In the given example, we create a list of KeyValuePair<int, string> like in the previous example. We then initialize the list with three KeyValuePair objects.

Lastly, we use a basic IEnumerator implementation to call the foreach loop and iterator over each KeyValuePair in the list.

Port: 3306, Database: MysSQL
Port: 9200, Database: Elasticsearch
Port: 6379, Database: Redis

Create a Dictionary of KeyValuePairs

One of the most common use case of the KeyValuePair struct is when dealing with dictionaries. This is because they share common traits and are easy to pair than the other collections such as lists and arrays.

An example is as follows:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Dictionary<int, string> dictionary = new Dictionary<int, string>
        {
            {3306, "MySQL"},
            {9200, "Elasticsearch"},
            {6379, "Redis"}
        };

        foreach (KeyValuePair<int, string> pair in dictionary)
        {
            Console.WriteLine($"Port: {pair.Key}, Database: {pair.Value}");
        }
    }
}

Like the previous example, we start by initializing a Dictionary<int, string> and use a foreach loop to iterate over the elements of the dictionary.

Port: 3306, Database: MySQL
Port: 9200, Database: Elasticsearch
Port: 6379, Database: Redis

Conclusion

In this tutorial, we walked you through the workings of the KeyValuePair struct in C# and how to use it to create key-value pairs.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list