Convert C# Dictionary to multidimensional array - c#

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

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

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.

Related

List to Jagged Array in C#

I have a list
List<int> list = new List<int>();
Now I want to add this to a Jagged Array
int[][] A = new int[][] { list.ToArray() };
This code on top is ok, but the problem is that all values in the list are add in the first block!
Well, then, this will be solved:
int[] x1 = list.ToArray();
int[][] A = new int[][] { new[] { x1[0] }, new[] { x1[1] }, new[] { x1[2] }, new[] { x1[3] } };
But (the code above) I've done this manually now, that's just the first four indexes I've of list put in the array..
How can I add entire list (all indexes) to my jagged array (with circles or other methods).
Use a projection.
This will iterate through the list, creating a new array with the sole value of the current iteration, and then end by creating an array of all of those arrays.
int[][] A = list.Select(i => new[] { i }).ToArray();
As an aside, and as [#maccettura] notes, this is a jagged array (where each member of the array is also an array itself).

Setting the value of an index of a string array to that of an item within an Enumerable array by using a "foreach" statement.

Is this the best way to set each item of a string array to that of an Enumerable array? I came up with this approach on my own, I tried to use my google-foo but couldn't really come up with coherent sentences to describe what i'm trying to do here..
string[] adapterDesc = new string[] {};
int i = 0;
foreach(NetworkInterface adapter in adapters)
{
adapterDesc[i] = adapter.Description;
i++;
}
...
No, that code will fail with an IndexOutOfRange exception because you have declared an array of strings that could contain zero elements.
So when you try to set the first element it will crash.
Instead you could use a List where you can add elements dynamically
List<string> adapterDesc = new List<string>();
foreach(NetworkInterface adapter in adapters)
{
adapterDesc.Add(adapter.Description);
}
...
A List is more flexible than an array because you don't have to know before the size of the array and you could still use it like it was an array
for(int x = 0; x < adapterDesc; x++)
{
Console.WriteLine(adapterDesc[x]);
}
If you want to use Linq then you could even reduce your code to a single line with
string[] adapterDesc = NetworkInterface.GetAllNetworkInterfaces()
.Select(ni => ni.Description)
.ToArray();

Unable to cast object of type 'System.Object[,]' to type 'System.Object[]'

I have a dll which gives me as an output an Object[,]
{Name = "Object[,]" FullName = "System.Object[,]"}
I am trying to convert it to Object[] to be able to read it properly, as it is a two columns object.
I have tried to cast it Object[] values = (Object[])data;, but I obtained the error from the tittle:
Unable to cast object of type 'System.Object[,]' to type 'System.Object[]'.
Is there any easy way to perform this operation? I would like to make a dictionary out of it.
Thanks in advance
Rather than using it as an Object[] (which it isn't), use the System.Array API:
var dictionary = new Dictionary<string, string>(); // For example
Array array = (Array) data;
for (int i = 0; i < array.GetLength(0); i++)
{
string key = (string) array.GetValue(i, 0);
string value = (string) array.GetValue(i, 1);
dictionary[key] = value;
}
You can only cast an instance of any type to another one if it implements both types. However object[,] does not derive from object[] so you can´t cast it to that type. At least you should provide which dimension (/column) of the array you want to handle further.
However it is unlcear why you need this. If you´re only interested on the colums instead of the rows then you might simply call myArr[i, 0] or whatever column you´re interested in within a loop on the first dimension of the array.
If you want to iterate your multidimensional array you may either flatten it:
foreach(var on in myArray)
Console.WriteLine(o);
Which will simply loop all the elements without considering its position in the array or
for(int i = 0; i < myArray.GetLength(myColumnIndex); i++)
Console.WriteLine(myArray[i, myColumnIndex]);
Whereby you get only those elements within the given column.
Well of course you cannot cast a multidimensional array to an single dimension array. It is illegal. Check Casting
But as a solution to your problem could be the following logic
object[,] multiDimensionalArray = new object[,]
{
{1,2}, //first pair
{3,4}, //second pair
{5,6} //third pair
};
Dictionary<object, object> dict = new Dictionary<object, object>();
//total number of elements //number of dimensions
int pairs = multiDimensionalArray.Length / multiDimensionalArray.Rank;
//or you can use i < multiDimensionalArray.GetLength(0);
for(int i = 0; i < pairs; i++)
{
dict.Add(multiDimensionalArray[i, 0], multiDimensionalArray[i, 1]);
}

Error in a c# code

This code takes an array of char as parameter and return an array that contains each word of the array. No word can contain spaces. Might need some help as I get an error on tab[i][j] = str[counter], but I think you can tell what I want it to do.
public static char[][] split_string(char[] str)
{
char[][] tab = new char[20][];
int x = 1;
int counter = 0;
for (int i = 0; i < str.Length; i++)
{
for (int j = 0; j < str.Length; j++)
{
if (str[i] != ' ')
{
tab[i][j] = str[counter];
}
else
{
counter++;
break;
}
counter++;
}
}
return tab;
}
The immediate problem
When you declare char[][] tab = new char[20][];
you are creating an array of arrays of char, of size 20. That is an array that has 20 elements that are arrays of char, each one of those 20 arrays will be set to null.
So, when you try to do tab[i][j] = str[counter]; you are trying to set the element on the index 'j´ of the array on the index 'i' of the array tabs, but the array on the index 'i' of the array 'tabs' is null (as all the other arrays in the array 'tabs' are). So you get a NullReferenceException.
In general, if you get a NullReferenceException it means that some reference is null, duh. It probably means you forgot to initilize something... You wil be pointed to where it happened, and it would be your work to figure out what was null there, why is it null, question yourself if it is right that it is null... if it is not, then fix it by intializing the variable. If it is, then check for null and do the appropiate thing for that case.
In your particular case, it shouldn't be null. So you have to initilize it. Initialize what? The array that you will be filling. Remember that when you said new char[20][]; you created an array of 20 arrays that are set to be null, but you don't want them to be null, but arrays.
So a simple tab[i] = new char[str.Length]; befor the inner loop will solve the immediate problem.
The other problem
Ok, but you will face another problem once that one is fixed. You see, you are creating an array of 20 elements. But the array you get on the parameter str maybe longer. So - when that happens - you will get an IndexOutOfRangeException as you try to write beyond the element of index 19 of your array.
And honestly... It is hard to infer from the code what you are trying to do.
What you are trying to do
Guessing from the signature of the method, I guess you want to take an array of chars and return and array of arrays of chars, where wach array contains a word.
And for some mysterious reasons you are not using string. If I'm right, the method that you should be using is string.Split.
These are my guesses for the mysterious reasons:
You are victim of a sadict teacher that wants you to not use string, List or anything like that.
You need to do interop with some system that only understand arrays of chars.
You used the wrong language tag, and this is a C question instead of a C# one.
Ok, let's assume it is the interop case. You can do this:
1) Create a new array from the char array:
new string(str)
2) Call split on it:
(new string(str)).Split(' ')
3) Convert each returned string into a char array:
from string s in (new string(str)).Split(' ') select s.ToCharArray()
4) Conver the resulting collection to an array:
(from string s in (new string(str)).Split(' ') select s.ToCharArray()).ToArray();
5) wrap it on a method:
public static char[][] split_string(char[] str)
{
return (from string s in (new string(str)).Split(' ') select s.ToCharArray()).ToArray();
}
Ok, you can do it without LINQ:
public static char[][] split_string(char[] str)
{
var list = new List<char[]>();
foreach (string s in (new string(str)).Split(' '))
{
list.Add(s.ToCharArray());
}
return list.ToArray();
}
But that is all trash, this is what you should be doing:
1) Accept an string:
public static char[][] split_string(string str)
{
var list = new List<char[]>();
foreach (string s in str.Split(' '))
{
list.Add(s.ToCharArray());
}
return list.ToArray();
}
2) return using string:
public static string[] split_string(string str)
{
var list = new List<string>();
foreach (string s in str.Split(' '))
{
list.Add(s);
}
return list.ToArray();
}
3) get rid of the stuffing:
public static string[] split_string(string str)
{
return str.Split(' ');
}
4) Why did you declare a method anyway?
// ...puff...

List box conversion to array int

I'm trying to convert a listbox to an array:
var modarray = listBox1.Items.Cast<String>().ToArray();
but then I also need to use an int array so I tried the following:
int[] arr = modarray.Cast<int>().ToArray();
I get an error that suggests that is not possible to convert the array. Can anybody help me please?
Try this:
int[] arr = modarray.Select(int.Parse).ToArray();
This will use the int.Parse() method for each of the strings in the original array to create a new integer array.
Try this instead :
int[] arr = modarray.Select(I => Convert.ToInt32(I)).ToArray();
.Cast<int>() is like foreach (var i in list) yield return (int)i;
Which if your items are strings underneath will fail.
I believe you need: int[] arr = modarray.Select(s => Int32.Parse(s)).ToArray();

Categories

Resources