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.
Please help! Thanks,
~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.
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());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.