How to convert a dictionary to a list in C#
By FoxLearn 12/20/2024 8:59:05 AM 12
Converting a dictionary to a list is a common task, and C# provides a few simple ways to achieve this using LINQ or loops.
1. Convert a Dictionary to a List of KeyValuePair
The simplest way to convert a dictionary to a list is by using the LINQ ToList()
method. This method will convert each key-value pair into a KeyValuePair<TKey, TValue>
in a list.
using System.Collections.Generic; using System.Linq; var dictionary = new Dictionary<int, string>() { [100] = "Bob", [101] = "Tom", [102] = "Teddy" }; var list = dictionary.ToList(); foreach(var kvp in list) { Console.WriteLine($"{kvp.Key}={kvp.Value}"); }
Output:
100=Bob 101=Tom 102=Teddy
When used on a dictionary, the ToList()
method returns a list of KeyValuePair
objects, where each KeyValuePair
contains a key and its corresponding value from the dictionary.
2. Convert Dictionary Keys to a List
If you only need the keys from the dictionary, you can use ToList()
on the Dictionary.Keys
collection.
var list = dictionary.Keys.ToList(); foreach(var key in list) { Console.WriteLine(key); }
Output:
100 101 102
3. Convert Dictionary Values to a List
If you are only interested in the values of the dictionary, you can use ToList()
on the Dictionary.Values
collection.
var list = dictionary.Values.ToList(); foreach(var val in list) { Console.WriteLine(val); }
Output:
Bob Tom Teddy
4. Convert Dictionary to a List of Tuples
To convert a dictionary to a list of tuples, you can use LINQ's Select()
method to project each key-value pair as a tuple. The result can then be converted to a list using ToList()
.
var list = dictionary.Select(kvp => (Id: kvp.Key, Name: kvp.Value)).ToList(); foreach(var tuple in list) { Console.WriteLine($"{tuple.Name} has id {tuple.Id}"); }
Output:
Bob has id 100 Tom has id 101 Teddy has id 102
5. Using a Loop to Convert Dictionary to a List
Sometimes you might want more control over how the dictionary is converted to a list. You can manually loop through the dictionary and add items to a list as needed.
var list = new List<KeyValuePair<int, string>>(); foreach(var kvp in dictionary) { if (kvp.Key > 100) { list.Add(kvp); } } Console.WriteLine($"List has {list.Count} items");
Output:
List has 2 items
- How to use BlockingCollection in C#
- Calculating the Distance Between Two Coordinates in C#
- Could Not Find an Implementation of the Query Pattern
- Fixing Invalid Parameter Type in Attribute Constructor
- Objects added to a BindingSource’s list must all be of the same type
- How to use dictionary with tuples in C#
- Dictionary with multiple values per key in C#
- Sock Merchant Problem Solution