difference between double[*,*] to double[][] in c# - 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.

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

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.

Passing dynamic arrays into the argument

I have a class constructor accepting params T[][] arrays.
public CartesianProduct(params T[][] arrays)
{
}
I am passing the arrays below which is working fine
string[] arr1 = { "MSG1" };
string[] arr2 = { "OFFER1", "OFFER2" };
string[] arr3 = { "CTA1", "CTA2" };
var cross = new CartesianProduct<string>(arr1,arr2,arr3);
This works fine if i know the number of arrays and then pass it in the argument. The problem is when i am creating a button in the windows form to add new arrays. For example i have a simple text box and a button which creates an array. Click Add new array will create another array. How can i pass these arrays in the argument? Help would be appreciated . Thanks in advance
You can not dynamically add a 4th parameter to the call. You can dynamically create an array containing an arbitrary number of other arrays and pass that:
var aList = new List<string[]>();
aList.Add(arr1);
//...
var cross = new CartesianProduct<string>(aList.ToArray());
You may consider adding another constructor that accepts a List directly.

Is it possible to prevent foreach from flattening rectangular arrays?

using System;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
int[,] x = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 10, 11, 12 } };
foreach (var i in x)
{
foreach (var j in i)
{
Console.WriteLine(j);
}
}
}
}
}
I noticed that var i in x flattens the array so it generates the following errors for the second foreach.
Error 1 foreach statement cannot operate on variables of type 'int'
because 'int' does not contain a public definition for 'GetEnumerator'
Is it possible to prevent foreach from flattening rectangular arrays?
Multidimensional array is, in some sense, a one-dimensional array that uses dimension information for accessing data as if they were really stored in two dimensions. Because of that when accessed by many methods (e.g. from class Array) and foreach iteration it's being treated as one-dimensional array, as this is the actual layout in memory. Otherwise during iteration new one-dimensional arrays would need to be created for every row.
You can try doing following things to achieve what you want:
Using jagged array instead of multidimensional one: int[][].
Creating extension method IEnumerable<IEnumerable<T>> ByRows<T>(this T[,] array) that would create iterator that does the proper iteration over rows. Obviously rows would either be a single-dimensional arrays, or another custom iterator that would iterate over contents of the row.
Skip the foreach entirely and use two nested for loops.
If you have a jagged array it won't behave this way (ie an array declared as int[][] rather than int[,]) Foreach is designed to enumerate each element and in the 2D array each element is an int, not an int array (despite the static initializer making it look like it's an array of arrays it's not). If you want to make it work as is (with a 2D array), I suggest using a conventional for loop instead of foreach.
The problem isn't so much in foreach, it's in the implementation of the enumerator returned from GetEnumerator. What it's doing is treating the multidimensional array as one contiguous array of values (and that's what it is in memory).
If you think about how you'd have to implement an enumerator so that it gave you your desired behaviour, it would basically be enumerating over an IEnumerable. This is effectively an array of arrays. C# represents this with jagged arrays, or int[][], as others have mentioned.
Conversely, multidimensional arrays are modelled in C# as one piece of memory that you index with two indices. You can't index the multidimensional array with one index and get back an array, as you can with jagged arrays. In fact, if you try to index a multidimensional array with one index, you get a compile error. You could implement the multidimensional array as a single dimension array, and do the math to translate a two dimensional index into a single dimensional index yourself.

Array of Arrays in C#

I need to know how to initialize array of arrays in C#..
I know that there exist multidimensional array, but I think I do not need that in my case!
I tried this code.. but could not know how to initialize with initializer list..
double[][] a=new double[2][];// ={{1,2},{3,4}};
Thank you
PS: If you wonder why I use it: I need data structure that when I call obj[0] it returns an array.. I know it is strange..
Thanks
Afaik, the most simple and keystroke effective way is this to initialize a jagged array is:
double[][] x = new []{new[]{1d, 2d}, new[]{3d, 4.3d}};
Edit:
Actually this works too:
double[][] x = {new[]{1d, 2d}, new[]{3d, 4.3d}};
This should work:
double[][] a = new double[][]
{
new double[] {1.0d, 2.0d},
new double[] {3.0d, 4.0d}
};
As you have an array of arrays, you have to create the array objects inside it also:
double[][] a = new double[][] {
new double[] { 1, 2 },
new double[] { 3, 4 }
};
double[][] a = new double[][] {
new double[] {1.0, 1.0},
new double[] {1.0, 1.0}
};
I don't know if I'm right about this, but I have been using socalled Structures in VB.net, and wondering how this concept is seen in C#. It is relevant to this question in this way:
' The declaration part
Public Structure driveInfo
Public type As String
Public size As Long
End Structure
Public Structure systemInfo
Public cPU As String
Public memory As Long
Public diskDrives() As driveInfo
Public purchaseDate As Date
End Structure
' this is the implementation part
Dim allSystems(100) As systemInfo
ReDim allSystems(1).diskDrives(3)
allSystems(1).diskDrives(0).type = "Floppy"
See how elegant all this is, and far better to access than jagged arrays. How can all this be done in C# (structs maybe?)

Categories

Resources