List to Jagged Array in C# - 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).

Related

Convert C# Dictionary to multidimensional array

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.

How can i compare arrays in two jagged arrays C#

Ok so i have 2 jagged arrays, i want to loop through them and compare each array to every array in the other jagged array.
So in this example i want to return true when access[1] == visual[0].
But it seems i cannot explicitly compare arrays in the jagged arrays. How can i reference the arrays as a whole and not only the elements within those arrays?
By this i mean if i write access[0][0] i will get "10". But i can't write access[0] to get "10","16"
string[][] access = new string[][] {
new string[] {"10","16"},
new string[] {"100","20"},
new string[] {"1010","2"},
new string[] {"1011","1"}
};
string[][] visual = new string[][] {
new string[] {"100","20"},
new string[] {"101","36"},
new string[] {"101","37"},
new string[] {"101","38"}
};
But i can't write access[0] to get "10","16"
You can. But to compare the elements you need to use Enumerable.SequenceEqual.
if (Enumerable.SequenceEqual(access[1], visual[0])) { ... }

c # - copying elements of one array to another - compile error

Learning some basics.. I'm trying to copy elements of an array to another. Let's say I don't know the size of the array 'bar'. So, I create an empty array 'arr' to copy the elements to bar into. The code below doesn't work.
It works if I replace
string[] arr ={} to string[] arr ={"",""}
How to declare an empty array and what should I modify in my code to achieve my goal?
Thanks!
//code
string[] bar = {"test", "user"};
string[] arr = {};
//iterate from the first to the last element of array bar
for (int i =0;i<bar.Length-1;i++)
{
Console.WriteLine("copy");
//copy string from bar to arr
arr[i]= bar[i];
//display the copied content from new array
Console.WriteLine(arr[i]);
}
in C#, arrays are of a fixed size. So when you create your array with size 0, you can't change the number of items it will contain, without re-instantiating it.
If you want to use a collection you can actively add/remove from (as is very common), consider using a List<T>:
string[] bar = {"test", "user"};
List<string> list = new List<string>();
for (int i =0;i<bar.Length-1;i++)
{
list.Add(bar[i]);
Console.WriteLine(list[i]);
}
By string[] arr = {}; you're instantiating an empty array of ZERO length, thus you need to define it like string[] arr = string[bar.Length];.
UPD:
Your code worked with string[] arr = {"",""}, because in this case you defined an array of length 2 using a two empty strings, but that's a code smell.
Arrays are fixed in size, which is why things like Lists are preferred over them.
In the case where you change your array definition to: string[] arr ={"",""} you are defining an array with a size of 2, same as your original array. When you try to copy it, the compiler already has everything allocated and ready to go, so it knows where position 0 and position 1 are in the array arr.
In the example in your code, where you have the array defined by string[] arr = {}; you are giving it an empty array (array size 0). The compiler has an issue, because it cannot reference position 0 or position 1 on an array that is empty.
You can modify the line as:
string[] arr = new string[4];
or
List<string> arr = new List<string>();
If you're going to use arrays, you'll want to create the second array as the same size as the first.
string[] bar = {"test", "user"};
string[] arr = new string[bar.Length];
If you know ahead of time that your array will be two, then you can just create it to be size two. Otherwise you'll want to inspect the size of the array you're copying from. If you know that you'll be adding and/or removing items, you'll want to use a different collection.

difference between double[*,*] to double[][] in c#

i used
double [,] marks=new double[26,5]
int[] function = object.verify(marks)
public void verifymarks(double[][] marks)
error i get is cannot convert from double[,] to double[][]
i tried to search in the internet but couldnot find any solution. I have just began to use c#. Please Help. THankx in advance
double[][] is jagged. It's literally an array of arrays.
double[,] is multidimensional. It gets special compiler treatment.
They have different memory layouts. double[][] is an array which holds references to the other arrays, while double[,] is laid out single-dimensionally for easier use.
Another difference is what data they can hold. A jagged array can be like this:
1231243245345345345345
23423423423423
2342342343r234234234234234234
23423
While a multidimensional array has to be a perfect table, like this:
34534534534534
34534534534533
34534534534534
34534534534545
A way to get around it would be to use nullable ints.
Now, to solve your problem:
Change your method signature to public void verifymarks(double[,] marks) and in the method change anything that uses marks[x][y] to marks[x,y].
double[][] is called a Jagged array. It is an array of array (the same way you could create a list of list). With this structure you can specify a different size for each sub-array.
For exemple:
double[][] jaggedArray = new double[2][];
jaggedArray[0] = new double[5];
jaggedArray[1] = new double[151];
The other writing double[,] is a 2D array (Multidimensional array in general). You can see it as a table.
A very handy feature of multidimensional array is the initialization:
string[,] test = new string[3, 2] { { "one", "two" },
{ "three", "four" },
{ "five", "six" } };
Here's a visual, from LINQPad's Dump() function.
The first is the double[,], which creates a matrix. The second is double[][], which is just an array of arrays.

Dynamic array in C#

Is there any method for creating a dynamic array in C#?
Take a look at Generic Lists.
Expanding on Chris and Migol`s answer with a code sample.
Using an array
Student[] array = new Student[2];
array[0] = new Student("bob");
array[1] = new Student("joe");
Using a generic list. Under the hood the List<T> class uses an array for storage but does so in a fashion that allows it to grow effeciently.
List<Student> list = new List<Student>();
list.Add(new Student("bob"));
list.Add(new Student("joe"));
Student joe = list[1];
Sometimes plain arrays are preferred to Generic Lists, since they are more convenient (Better performance for costly computation -Numerical Algebra Applications for example, or for exchanging Data with Statistics software like R or Matlab)
In this case you may use the ToArray() method after initiating your List dynamically
List<string> list = new List<string>();
list.Add("one");
list.Add("two");
list.Add("three");
string[] array = list.ToArray();
Of course, this has sense only if the size of the array is never known nor fixed ex-ante.
if you already know the size of your array at some point of the program it is better to initiate it as a fixed length array. (If you retrieve data from a ResultSet for example, you could count its size and initiate an array of that size, dynamically)
List<T> for strongly typed one, or ArrayList if you have .NET 1.1 or love to cast variables.
You can do this with dynamic objects:
var dynamicKeyValueArray = new[] { new {Key = "K1", Value = 10}, new {Key = "K2", Value = 5} };
foreach(var keyvalue in dynamicKeyValueArray)
{
Console.Log(keyvalue.Key);
Console.Log(keyvalue.Value);
}
Use the array list which is actually implement array. It takes initially array of size 4 and when it gets full, a new array is created with its double size and the data of first array get copied into second array, now the new item is inserted into new array.
Also the name of second array creates an alias of first so that it can be accessed by the same name as previous and the first array gets disposed
Dynamic Array Example:
Console.WriteLine("Define Array Size? ");
int number = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter numbers:\n");
int[] arr = new int[number];
for (int i = 0; i < number; i++)
{
arr[i] = Convert.ToInt32(Console.ReadLine());
}
for (int i = 0; i < arr.Length; i++ )
{
Console.WriteLine("Array Index: "+i + " AND Array Item: " + arr[i].ToString());
}
Console.ReadKey();
you can use arraylist object from collections class
using System.Collections;
static void Main()
{
ArrayList arr = new ArrayList();
}
when you want to add elements you can use
arr.Add();
This answer seems to be the answer you are looking for Why can't I do this: dynamic x = new ExpandoObject { Foo = 12, Bar = "twelve" }
Read about the ExpandoObject here https://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject(v=vs.110).aspx
And the dynamic type here https://msdn.microsoft.com/en-GB/library/dd264736.aspx

Categories

Resources