To convert a dictionary to an array of key-value pairs in C#, you can use the `ToArray` method from the `System.Linq` namespace on the dictionary's `KeyValuePair
We can convert a dictionary to an array of key-value pairs in C# using the `ToArray` method. This example demonstrates how to declare and initialize a dictionary, use the `ToArray` method to convert the dictionary to an array of key-value pairs, and print the array of key-value pairs.
For example,
using System.Collections.Generic;
and using System.Linq;
.myDictionary
with integer keys and string values.using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// Declare and initialize a dictionary
Dictionary<int, string> myDictionary = new Dictionary<int, string>
{
{1, "One"},
{2, "Two"},
{3, "Three"}
};
// Convert the dictionary to an array of key-value pairs
KeyValuePair<int, string>[] keyValueArray = myDictionary.ToArray();
// Print the array of key-value pairs
Console.WriteLine("Array of key-value pairs:");
foreach (var kvp in keyValueArray)
{
Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
}
}
}
Array of key-value pairs: Key: 1, Value: One Key: 2, Value: Two Key: 3, Value: Three
We can convert an empty dictionary to an array of key-value pairs in C# using the `ToArray` method. This example demonstrates how to declare and initialize an empty dictionary, use the `ToArray` method to convert the dictionary to an array of key-value pairs, and print the array of key-value pairs.
For example,
using System.Collections.Generic;
and using System.Linq;
.myDictionary
.using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// Declare and initialize an empty dictionary
Dictionary<int, string> myDictionary = new Dictionary<int, string>();
// Convert the dictionary to an array of key-value pairs
KeyValuePair<int, string>[] keyValueArray = myDictionary.ToArray();
// Print the array of key-value pairs
Console.WriteLine("Array of key-value pairs:");
foreach (var kvp in keyValueArray)
{
Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
}
}
}
Array of key-value pairs:
In this tutorial, we learned How to Convert a Dictionary to an Array of Key-Value Pairs in C# language with well detailed examples.