1

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.

0

3 Answers 3

7
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.

Sign up to request clarification or add additional context in comments.

2 Comments

That's neither an array nor a list. You need either .ToList() or .ToArray() to realise it as a collection, now it's just an enumerator that can read from the dictionary.
@Guffa Yep, that is true. I left it out on purpose but I suppose according to the question it should be brought to the OPs attention.
1

You can do it like this:

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.