In C#, dictionaries (Dictionary<TKey, TValue>
) are widely used for key-value pair storage, offering fast lookups and efficient data retrieval. However, there are times when you need to convert a dictionary into a list (List<T>
), whether for LINQ operations, data transformations, or serialization purposes.
In this blog post, we'll explore various ways to convert a Dictionary<TKey, TValue>
into different types of lists while maintaining performance and code clarity. We’ll cover:
Converting a dictionary’s keys to a list
Converting a dictionary’s values to a list
Converting a dictionary’s key-value pairs to a list of tuples or objects
Advanced scenarios using LINQ and performance optimizations
Let’s dive in!
1. Converting Dictionary Keys to a List
If you only need a list of keys from a dictionary, you can use the Keys
property and convert it to a list using ToList()
:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
Dictionary<int, string> sampleDictionary = new()
{
{ 1, "Apple" },
{ 2, "Banana" },
{ 3, "Cherry" }
};
List<int> keyList = sampleDictionary.Keys.ToList();
Console.WriteLine(string.Join(", ", keyList)); // Output: 1, 2, 3
}
}
Performance Considerations
The Keys
property returns a Dictionary<TKey, TValue>.KeyCollection
, which is a lightweight wrapper. However, calling .ToList()
creates a new list in memory. If you only need an enumerable collection, consider using Keys
directly instead of converting it to a list.
2. Converting Dictionary Values to a List
Similarly, if you need only the values, use the Values
property and convert it to a list:
List<string> valueList = sampleDictionary.Values.ToList();
Console.WriteLine(string.Join(", ", valueList)); // Output: Apple, Banana, Cherry
Like Keys
, the Values
property returns a Dictionary<TKey, TValue>.ValueCollection
, which can be used as an IEnumerable<T>
without conversion if mutation is not required.
3. Converting Dictionary Entries to a List of KeyValuePairs
Sometimes, you may want to work with both keys and values together. The simplest way is to convert the dictionary into a List<KeyValuePair<TKey, TValue>>
:
List<KeyValuePair<int, string>> keyValuePairList = sampleDictionary.ToList();
foreach (var kvp in keyValuePairList)
{
Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
}
This method is straightforward and preserves the dictionary’s structure while allowing list operations such as sorting or filtering.
4. Converting Dictionary to a List of Tuples
Another approach is to transform the dictionary into a list of tuples, which can be beneficial in certain functional programming scenarios:
List<(int Key, string Value)> tupleList = sampleDictionary.Select(kvp => (kvp.Key, kvp.Value)).ToList();
Tuples provide lightweight, immutable representations of dictionary entries without the verbosity of KeyValuePair<TKey, TValue>
.
5. Converting Dictionary to a List of Custom Objects
For real-world applications, you often work with custom objects instead of KeyValuePair
or tuples. You can map dictionary entries to a custom class like this:
class Fruit
{
public int Id { get; set; }
public string Name { get; set; }
}
List<Fruit> fruitList = sampleDictionary.Select(kvp => new Fruit { Id = kvp.Key, Name = kvp.Value }).ToList();
This approach is particularly useful when integrating dictionary data into UI models or APIs.
6. Advanced Use Cases with LINQ
Filtering While Converting
You can filter dictionary entries before conversion using LINQ. For example, extracting only keys greater than 1:
List<int> filteredKeys = sampleDictionary.Where(kvp => kvp.Key > 1).Select(kvp => kvp.Key).ToList();
Sorting While Converting
If you need a sorted list, you can order dictionary entries before conversion:
List<KeyValuePair<int, string>> sortedList = sampleDictionary.OrderBy(kvp => kvp.Value).ToList();
This will order the dictionary by values alphabetically before converting it to a list.
7. Performance Considerations and Best Practices
Avoid Unnecessary Conversions: If you only need enumeration, prefer using
Keys
,Values
, or LINQ queries withoutToList()
.Be Mindful of Large Dictionaries: Converting large dictionaries to lists can increase memory usage. Use lazy evaluation (
IEnumerable<T>
) where possible.Use
Select
Efficiently: If transforming dictionary entries,Select()
avoids unnecessary object creation.
Conclusion
Converting a C# dictionary into a list is a common operation with multiple approaches depending on your use case. Whether extracting keys, values, or key-value pairs, understanding the best method ensures efficiency and maintainability in your code.
By leveraging LINQ, custom objects, and performance considerations, you can seamlessly transition between dictionaries and lists in your .NET applications. Keep these best practices in mind to write clean and optimized C# code!