Array of Arrays in C# - 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?)

Related

How to convert php array to c# array?

I want to assign value of tax_id, found a solution in php but i want to implement in c#, Please have a look
this is php code,'tax_id'=>array(array(6,0,array(13)))
can anyone convert this code snippets in c#, thanks
Perhaps you wan't a 3D Jagged array:
var jagged3D= new int[][][]
{
new int[][]{
new int[]{6},
new int[]{0},
new int[]{13}
}
};
Or a 2DJagged of a custom object
var jaggedCustom = new Custom[][] {
new Custom[]{
new Custom{
A =3,
B =0,
C = new int[]{13}
}
}
};
But all element of an array has the same type. You can learn more about Single-Dimensional Arrays, Multidimensional Arrays, Jagged Arrays with Msdn documentation. Using the left panel to navigate.

Apply "new" to only one dimension of multi-dimensional array?

I have this C# program, and it has the following code:
/*10 data for one peprson */
private int[] data = new int[10];
private void SomeMethod()
{
/*More code*/
this.data = new int[10];
/*More code*/
}
This program calls this method when an event occurs, and every time that happens, this one-dimensional array gets a "new" instance of an array of size 10, and refresh the array. Kinda like resetting it.
Now, I was told to write a new program that does the same thing, except that there are 5 people now. So I created a 2-dimensional array like
private int[,] data = new int[5, 10];
which will be able to store 10 data for each of the 5 people.
Now I am at a loss on how to refresh/reset only one person's data from this 2-d array. I tried
private void SomeMethod(int index) /*index 0 - 4 for each of the 5 people*/
{
this.data[index] = new int[10];
}
but this clearly does not work, and I get an error saying I am missing a dimension. Is there a way to achieve this?
For the time being, I am using
private void SomeMethod(int index) /*index 0 - 4 for each of the 5 people*/
{
for(int i=0; i<10; i++)
this.data[index, i] = 0;
}
When I tested it with the original code, I noticed that every time it got a "new" instance, it was assigning 0's to the array. Now the difference is that the original one is referencing the new instance with no data (and hence 0?), and the rewritten one is overwriting with 0's.
Do these two basically work the same way, program's-function-wise?
There's nothing wrong with the code you have. It's even likely faster than creating the new array. But if you really want to, you can use a jagged array instead:
private int[][] data = new int[5][];
//...
private void SomeMethod(int index) /*index 0 - 4 for each of the 5 people*/
{
this.data[index] = new int[10];
}
But arrays seem weird for this. A List<T> might be better:
private List<int[]> data = new List<int[]>();
where you can then use the .Add() method as you get new records, and use the Count property to know how many you've added.
Moreover, it's common to find out the int[10] array was actually a stand-in for named fields, where each position in the array has meaning. In that situation, you're usually much better off building a class for this data, where each item in the array is a named field in the class (we'll just call it MyClass for now). Then you end up with something like this:
private List<MyClass> data = new List<MyClass>();

How to convert list of objects with two fields to array with one of them using LINQ

It's hard for me to explain, so let me show it with pseudo code:
ObjectX
{
int a;
string b;
}
List<ObjectX> list = //some list of objectsX//
int [] array = list.Select(obj=>obj.a);
I want to fill an array of ints with ints from objectsX, using only one line of linq.
You were almost there:
int[] array = list.Select(obj=>obj.a).ToArray();
you need to just add ToArray at the end
The only problem in your code is that Select returns IEnumerable.
Convert it to an array:
int[] array = list.Select(obj=>obj.a).ToArray();

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