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?
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>>:
Select method loops over each pair in the dictionary, applying the given delegate to each pairstring.FormatToArray call converts a sequence into an arrayIf 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();