简体   繁体   English

如何转换字典 <int, long> 字符串数组/列表?

[英]How to convert Dictionary<int, long> to string array/list?

I would like to convert a Dictionary to a string array (or list) 我想将字典转换为字符串数组(或列表)
The string array needs to be returned like this: "ID, PTS" where int is ID and long is PTS. 字符串数组需要这样返回:“ ID,PTS”其中int是ID,而long是PTS。

Please help! 请帮忙! Thanks, 谢谢,
~Nikku. 〜Nikku。

var strings = dict.Select(item => string.Format("{0}, {1}", item.Key, item.Value));

Note that this returns an enumerator. 请注意,这将返回一个枚举数。 Whether you want the result in the form of string[] or List<string> you should use .ToArray() or .ToList() , respectively. 无论您要使用string[]还是List<string>形式的结果,都应分别使用.ToArray().ToList()

You can do it like this: 您可以这样做:

string[] arr =
  theDictionary
  .Select(kvp => kvp.Key.ToString() + ", " + kvp.Value.ToString())
  .ToArray();

The simple answer is to iterate over the dictionary, and copy the values into a string list. 简单的答案是遍历字典,然后将值复制到字符串列表中。

Dictionary<int, long> dict = new Dictionary<int, long>();

// If you like Linq. Stick a .ToArray() or .ToList() at the end, or leave it as IEnumerable<string>
var stringList = dict.Select(kvp => kvp.Key.ToString() + ", " + kvp.Value.ToString());

// If you don't like Linq.
List<string> stringList2 = new List<string>();
foreach (KeyValuePair<int, long> kvp in dict)
{
    stringList2.Add(kvp.Key.ToString() + ", " + kvp.Value.ToString());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM