我想将字典转换为C#中的数组.该数组应采用以下格式:
string[] array = {"key1=value1","key2=value2","key1=value1"}
Run Code Online (Sandbox Code Playgroud)
如何有效地做到这一点?
LINQ让这很容易:
string[] array = dictionary.Select(pair => string.Format("{0}={1}",
pair.Key, pair.Value))
.ToArray();
Run Code Online (Sandbox Code Playgroud)
这利用了IDictionary<TKey, TValue>实现的事实IEnumerable<KeyValuePair<TKey, TValue>>:
如果这是你第一次见到LINQ,我强烈建议你多看一下.这是一种处理数据的惊人方式.
在C#6中,string.Format代码可以用插值字符串文字替换,使其更紧凑:
string[] array = dictionary.Select(pair => $"{pair.Key}={pair.Value}")
.ToArray();
Run Code Online (Sandbox Code Playgroud)
string[] array = dictionary
.Select(kvp => string.Format("{0}={1}", kvp.Key, kvp.Value))
.ToArray();
Run Code Online (Sandbox Code Playgroud)