To convert a dictionary to an array of keys in C#, you can use the `Keys` property of the `Dictionary
We can convert a dictionary to an array of keys in C# using the `Keys` property and the `ToArray` method. This example demonstrates how to declare and initialize a dictionary, use the `Keys` property to get the keys, convert them to an array, and print the array of keys.
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 keys
int[] keysArray = myDictionary.Keys.ToArray();
// Print the array of keys
Console.WriteLine("Array of keys:");
foreach (int key in keysArray)
{
Console.WriteLine(key);
}
}
}
Array of keys: 1 2 3
We can convert an empty dictionary to an array of keys in C# using the `Keys` property and the `ToArray` method. This example demonstrates how to declare and initialize an empty dictionary, use the `Keys` property to get the keys, convert them to an array, and print the array of keys.
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 keys
int[] keysArray = myDictionary.Keys.ToArray();
// Print the array of keys
Console.WriteLine("Array of keys:");
foreach (int key in keysArray)
{
Console.WriteLine(key);
}
}
}
Array of keys:
In this tutorial, we learned How to Convert a Dictionary to an Array of Keys in C# language with well detailed examples.