Programmingempire
Today I will discuss KeyValuePair and its Applications. Basically, it is a collection in C# that combines two objects together – one is called a key, and another one is called a value. Essentially, it is a generic struct. The namespace System.Collections.Generic contains the KeyValuePair struct.
Creating a KeyPaluePair
We use the constructor KeyValuePair<TKey, TValue)(k, v) to create its instance as shown below. Evidently, we can create an instance of KeyValuePair using the generic type as well as using the Create() method of the static type.
using System;
using System.Collections.Generic;
namespace KeyValuePairExample
{
class Program
{
static void Main(string[] args)
{
KeyValuePair<int, string> k = new KeyValuePair<int, string>(10, "abc");
KeyValuePair<int, String> k1;
k1=KeyValuePair.Create<int, string>(20, "xyz");
Console.WriteLine(k);
Console.WriteLine(k1);
}
}
}
Output
KeyValuePair and its Applications
To illustrate the usage of this library struct, several examples are given below. Although we can use this data structure alone in many applications, we build other collections such as List, Linked List, HashSet, Dictionary and many more using key value pairs.
Creating a Linked List using Key-Value Pairs
As shown below, the instance of a generic collection class LinkedList takes the objects of KeyValuePair as its elements. Further, the foreach loop iterates through each element of the Linked List. Basically, each entry in this object represents the enrolment no. of a student as the key and the corresponding marks as its value.
using System;
using System.Collections.Generic;
namespace KeyValuePairExamples1
{
class Program
{
static void Main(string[] args)
{
LinkedList<KeyValuePair<int, int>> ob = new LinkedList<KeyValuePair<int, int>>();
ob.AddLast(new KeyValuePair<int, int>(1101, 70));
ob.AddLast(new KeyValuePair<int, int>(1102, 58));
ob.AddLast(new KeyValuePair<int, int>(1103, 89));
ob.AddLast(new KeyValuePair<int, int>(1104, 69));
ob.AddLast(new KeyValuePair<int, int>(1105, 80));
foreach (KeyValuePair<int,int> k in ob)
Console.WriteLine(k);
}
}
}
Output
Key and Value Properties
In fact, there are two significant properties of the KeyValuePair struct that make it very easy to work with it. These properties are the Key and the Value which represent the corresponding key and value in a particular instance. The following example shows their usage.
foreach (KeyValuePair<int, int> k in ob)
Console.WriteLine($"Key: {k.Key}, Value: {k.Value}");
Output
Using KeyValuePair in LINQ
Basically, Language Integrated Query (LINQ) is a feature of C# that enables us to write and execute queries using the language syntax. Besides, the data source can be objects also. The following example shows a query on the above-mentioned object of the Linked List.
//Selecting elements where value is more than 70
Console.WriteLine("Candidates having more than 70 marks...");
var q = from k in ob
where k.Value > 70
select k;
foreach (var v in q)
Console.WriteLine(v);
Output
Using Query Methods
Besides the query syntax, we can also use Query Methods to formulate a LINQ query. The following example shows the usage of Select() and Where() methods to find elements where the value is 70 or more. Finally, these methods return the desired key/value pairs.
//Selecting elements where value is 70 or more
Console.WriteLine("Candidates having 70 or more marks...");
var v = ob.Select(k => k).Where(k=>k.Value>=70);
foreach (var v1 in v)
Console.WriteLine(v1);
Output
Returning Two Values from a Method
As can be seen, the KeyValuePair stores the two data elements, we can use it in a method to return two values. The following example illustrates a method returning two values.
using System;
using System.Collections.Generic;
using System.Linq;
namespace KeyValuePairExamples1
{
class Program
{
static void Main(string[] args)
{
LinkedList<KeyValuePair<int, int>> ob = new LinkedList<KeyValuePair<int, int>>();
ob.AddLast(new KeyValuePair<int, int>(1101, 70));
ob.AddLast(new KeyValuePair<int, int>(1102, 58));
ob.AddLast(new KeyValuePair<int, int>(1103, 89));
ob.AddLast(new KeyValuePair<int, int>(1104, 69));
ob.AddLast(new KeyValuePair<int, int>(1105, 80));
//Display Changed values
var v2 = SetValues(ob);
Console.WriteLine($"Changed Value for Key {v2.Item1} is {v2.Item2}");
}
public static (int, int) SetValues(LinkedList<KeyValuePair<int, int>> mylist)
{
int a=0, b=0;
foreach(var v in mylist)
{
if (v.Key == 1103)
{
a = v.Key;
b = v.Value + 10;
}
}
return (a, b);
}
}
}
Output
Using KeyValuePair to Create a Dictionary
Finally, we can create a Dictionary from a number of Key/Value pairs. Further, this dictionary represents items in a shop. Consequently, the key is the name of the item, and the value is its price. Also, the example below also computes the minimum and maximum price in the collection.
using System;
using System.Collections.Generic;
using System.Linq;
namespace KeyValuePairExamples2
{
class Program
{
static void Main(string[] args)
{
//A Dictionary for Item and Price in a Shop
Dictionary<String, int> d1 = new Dictionary<string, int>() {
{ "Planter", 300 },
{ "Notebook", 50 },
{ "hair Dryer", 750 },
{ "Hand Cream", 149 },
{ "Dog Hoodie", 545},
{ "Assorted Cookies", 199 } };
foreach(KeyValuePair<string, int> k in d1)
{
Console.WriteLine($"Key: {k.Key}, Value: {k.Value}");
}
int min = d1.Select(a=>a).Min(a => a.Value);
int max = d1.Select(a => a).Max(a => a.Value);
Console.WriteLine($"Minimum Value: {min}, Maximum Value: {max}");
}
}
}
Output
Summary
This article explained the KeyValuePair and its Applications. To sum up, the KeyValuePair<TKey, TValue> is an important element of the Collection in the .NET Framework. Indeed, we create several collections such as dictionaries and lists using key-value pairs. Also, the Key and Value properties are helpful when we iterate through a collection.