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();
}
CodePudding user response:
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.
CodePudding user response:
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;
}