C# KeyValuePair Hints

C# KeyValuePair Hints

You need to store two values together in a single collection with the C# programming language. The KeyValuePair struct in System.Collections.Generic is ideal for this purpose, as it is simple and always available. Here we see ways you can use the KeyValueCollection struct in Lists, in methods, and in some algorithms.

Example

First, this example shows how you can use KeyValuePair in a List, which is also in System.Collections.Generic. This is useful for storing pairs of values in a single List. Alternatively, you could use two separate Lists, but that can complicate matters.

Program that uses KeyValuePair [C#]
using System;
using System.Collections.Generic;
class Program
{
 static void Main()
 {
 // Shows a List of KeyValuePairs.
 var list = new List<KeyValuePair<string, int>>();
 list.Add(new KeyValuePair<string, int>("Cat", 1));
 list.Add(new KeyValuePair<string, int>("Dog", 2));
 list.Add(new KeyValuePair<string, int>("Rabbit", 4));
 foreach (var element in list)
 {
 Console.WriteLine(element);
 }
 }
}
Output
[Cat, 1]
[Dog, 2]
[Rabbit, 4]

Overview. This code example shows how you can initialize a new List of type KeyValuePair. Inside the brackets in the KeyValuePair, there are two types separated by a comma. This examples shows KeyValuePairs of one string and one int each.

How to create new KeyValuePairs. Here we see that you can create a new KeyValuePair with its constructor. The constructor is shown in the List.Add calls. The KeyValuePair’s constructor returns the new KeyValuePair, and that instance is added.

Note on arrays. Instead of a List, you could use an array here. You can simply specify the KeyValuePair<string, int> as the type of the array. This would improve performance in many situations.

Return two values

Often, you need to return two separate values from a method. You can do this very easily with KeyValuePair. You must specify the exact type in the return value, and then return the new KeyValuePair in the method body. This is clearer than a two-element array. Consider out or ref parameters instead.

Program that returns two values [C#]
using System;
using System.Collections.Generic;
class Program
{
 static void Main()
 {
 Console.WriteLine(GetNames());
 }
 static KeyValuePair<string, string> GetNames()
 {
 // Gets collection of first and last name.
 string firstName = "William";
 string lastName = "Gates";
 return new KeyValuePair<string, string>(firstName, lastName);
 }
}
Output
[William, Gates]

Read-only compilation error

When using KeyValuePair in your program, you will likely get this error at some point. The C# compiler doesn’t allow you to assign the Key and Value properties. This must be assigned in the constructor.

Property or indexer ‘System.Collections.Generic.KeyValuePair<int,int>.Key’ cannot be assigned to—it is read only

Loop over Dictionary

Probably the most popular usage of KeyValuePair is in a loop over a Dictionary. The Dictionary collection in C# has an enumerator that returns each key and value in a KeyValuePair, one at a time. Examples are available.

Dictionary Examples

Using KeyValuePair with var. An improved syntax could be to use the var keyword with the foreach loop over your Dictionary. This replaces the lengthy KeyValuePair type declaration with three letters.

Foreach Loop Examples

Sort

How can you sort a collection of KeyValuePair instances? You can implement a custom sorting Comparison method. The linked tutorial contains information on this approach.

Sort KeyValuePair List

Shuffle array

As shown in the first example, you may use KeyValuePair in a List to create two parallel Lists. These are very easily sorted, keeping both values together. This site has an example of an accurate shuffle algorithm with KeyValuePair and List.

Shuffle Array

Implementation

You should know what the basic layout of the KeyValuePair struct is. Here, we see the internal code. The KeyValuePair has two private fields, and two public properties that retrieve the values of those fields. The constructor is also shown.

Implementation of KeyValuePair [C#]
[Serializable, StructLayout(LayoutKind.Sequential)]
public struct KeyValuePair<TKey, TValue>
{
 private TKey key;
 private TValue value;
 public KeyValuePair(TKey key, TValue value);
 public TKey Key { get; }
 public TValue Value { get; }
 public override string ToString();
}

ToString method

The ToString method is very useful in KeyValuePair. When you want to display the values, simply call ToString() or pass the KeyValuePair to Console.Write or Console.WriteLine. This will implicitly call ToString(). Internally, ToString() uses a StringBuilder.

Should I use KeyValuePair?

Sometimes. In many cases, such as with internal method code, using KeyValuePair is very convenient and simple. However, using a class or struct you define yourself can definitely enhance the object-orientation of your program. I suggest you prefer classes when the usage is non-trivial.

Summary

In this article, we saw examples of using KeyValuePair in the C# language, and also looked into its internals in the .NET Framework. Lists and Dictionaries are ideal companions for KeyValuePairs. We also saw how you can return the collection from methods.

Collections

Reference:

http://www.dotnetperls.com/keyvaluepair

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s