3

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?

2 Answers 2

5
string[] array = dictionary
                .Select(kvp => string.Format("{0}={1}", kvp.Key, kvp.Value))
                .ToArray();
Sign up to request clarification or add additional context in comments.

Comments

5

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.