C# Dictionary to List: Convert Keys & Values

To change a Dictionary in C# to a List, you can use the Keys and Values properties of the Dictionary. You can use the Keys property to get all the keys in the Dictionary and the Values property to get all the values. Then use the List constructor to convert the keys and values into a List. Here is an example:

Dictionary<string, int> myDictionary = new Dictionary<string, int>();
myDictionary.Add("Apple", 1);
myDictionary.Add("Banana", 2);
myDictionary.Add("Orange", 3);

List<string> keys = new List<string>(myDictionary.Keys);
List<int> values = new List<int>(myDictionary.Values);

Console.WriteLine("Keys:");
foreach (string key in keys)
{
    Console.WriteLine(key);
}

Console.WriteLine("Values:");
foreach (int value in values)
{
    Console.WriteLine(value);
}

Output:

Keys:
Apple
Banana
Orange
Values:
1
2
3

In the above example, we first defined a Dictionary object and added some key-value pairs to it. We then converted the keys to a List using the Keys property and the values to a List using the Values property. Finally, we used a foreach loop to print the elements in the List.

bannerAds