开发者

Convert a Dictionary<string,string> to an array

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?


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜