4

I am trying to convert Dictionary<string, string> to multidimensional array. The items inside multidimentional array should be in quotes. So far I get this ["[mary, online]","[alex, offline]"]. But the output should be something like [["mary", "online"], ["alex", "offline"]]. Please help.

public void sendUpdatedUserlist(IDictionary<string, string> message)
{
    string[] array = message
      .Select(item => string.Format("[{0}, {1}]", item.Key, item.Value))
     .ToArray();
}
3
  • Do you mean a multidimensional array like string[,] or a jagged array like string[][]? Commented Dec 19, 2022 at 21:21
  • Instead of string.Format do new string[]{ item.key,item.value} ? Commented Dec 19, 2022 at 21:21
  • You should probably use a real JSON serializer for this. Will save you from fighting a bunch of edge case bugs and probably run faster as a bonus. Commented Dec 19, 2022 at 21:35

2 Answers 2

3

If you insist on 2d array (string[,], not jagged string[][]) you can create the array and fill it row by row:

string[,] array = new string[message.Count, 2];

int index = 0;

foreach (var pair in message) {
  array[index, 0] = pair.Key;
  array[index++, 1] = pair.Value; 
}
Sign up to request clarification or add additional context in comments.

Comments

2

string.Format isn't going to return an array, you're close, but what you want is to "select" an actual array. Something like this:

var arr = dict.Select(kvp => new[] { kvp.Key, kvp.Value }).ToArray();

this is going to return type of string[][], which is technically a jagged array (unlike a true 2D array string[,] in that each dimension doesn't have to be the same size) unlike the one-dimensional string[] you have declared in your sample code.

If you truly need a 2D array, you can't really do that with LINQ and .ToArray(), you'll have to populate it yourself with a loop.

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.