Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a Dictionary<string,string> to an array

Tags:

.net

c#-3.0

I want to convert a Dictionary to an array in C#. The array should be in the following format:

string[] array = {"key1=value1","key2=value2","key1=value1"}

How to do this effectively?

like image 959
Satish Appasani Avatar asked Jan 23 '26 22:01

Satish Appasani


2 Answers

string[] array = dictionary
                .Select(kvp => string.Format("{0}={1}", kvp.Key, kvp.Value))
                .ToArray();
like image 171
Gabe Avatar answered Jan 26 '26 12:01

Gabe


LINQ makes that really easy:

string[] array = dictionary.Select(pair => string.Format("{0}={1}",
                                                         pair.Key, pair.Value))
                           .ToArray();

This takes advantage of the fact that IDictionary<TKey, TValue> implements IEnumerable<KeyValuePair<TKey, TValue>>:

  • The Select method loops over each pair in the dictionary, applying the given delegate to each pair
  • Our delegate (specified with a lambda expression) converts a pair to a string using string.Format
  • The ToArray call converts a sequence into an array

If this is the first time you've seen LINQ, I strongly recommend that you look at it more. It's an amazing way of dealing with data.

In C# 6, the string.Format code can be replaced with interpolated string literals, making it rather more compact:

string[] array = dictionary.Select(pair => $"{pair.Key}={pair.Value}")
                           .ToArray();
like image 42
Jon Skeet Avatar answered Jan 26 '26 11:01

Jon Skeet