How to populate array with arrays of objects - c#

for (int i = 0; i < People.Length; i++) {
People[i] = new Person(first[i], last[i], birth[i]);
}
Now first and last contain 20 strings and birth is a DateTime object that again populates the array people with 20 birthdates. I just need to know how to correctly initialize my array.

You have to use Jagged Array
ex:
You can initialize jagged arrays like this example:
int[][] numbers = new int[2][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} };
You can also omit the size of the first array, like this:
int[][] numbers = new int[][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} };

You initialize your array with the desired size:
Person[] people = new Person[20];
To automatically use the length of, for example, first:
Person[] people = new Person[first.Length];

Related

Initialize array of arrays with a set array length

I want to initialize an array of arrays like in java:
int[][] arrPos=new int[16][48];
int[][] arrPosOther=new int[16][48];
and I can set a row array value like this:
arrPos[0]=arrPosOther[0];
and I can set a cell value like this:
arrPos[1][0]=125;
but in C#, I can declare only like this:
int[][] arrPos=new int[16][];
can not set the column value in the initialization.
It seems like you are trying to find a way to initialize Jagged array in c#: please refer to the following example:
int[][] jaggedArray2 = new int[][]
{
new int[] {1,3,5,7,9},
new int[] {0,2,4,6},
new int[] {11,22}
};
The short form for the same sample is shown below:
int[][] jaggedArray2 =
{
new int[] {1,3,5,7,9},
new int[] {0,2,4,6},
new int[] {11,22}
};
You can also perform the initialization in several steps:
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[5];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[2];
jaggedArray[0] = new int[] { 1, 3, 5, 7, 9 };
jaggedArray[1] = new int[] { 0, 2, 4, 6 };
jaggedArray[2] = new int[] { 11, 22 };
And, apparently, you can implement a sort of for or foreach loop in order to populate the array from some data structure. More reading available at: http://msdn.microsoft.com/en-us/library/2s05feca.aspx
Also, you should probably consider a use of multidimensional array, like int[,] (the C# syntax in this case is different from Java lang).
Hope this will help.
There is no syntax you are looking for.
One statement option could be
int[][] arrPos = Enumerable.Range(0, length).Select(_ => new int[length]).ToArray();

two dimension array; one dimension length is defined one is undefined in c#

I want to make an array which one dimension's length is defined but the other one is undefined
I try to do it with "LIST" and I dont know how to make a two dimension array which I already know how much is the length of one dimension
Make an array of lists. But make sure you include System.Collections.Generic in your class:
using System;
using System.Collections.Generic;
in the body of the method or class where you need this:
var arrayOfList = new List<int>[10];
for (var i = 0; i < 10; i++)
{
// initialize each entry of the array
arrayOfList[i] = new List<int>();
}
// add some stuff to entry one at a time
arrayOfList[0].Add(1);
// add some integers as a range
arrayOfList[0].AddRange(new [] {2, 3, 4});
// add some stuff to entry 1
arrayOfList[1].AddRange(new [] {5, 6});
If you don't want to use the generic list class, you can do a jagged array but it isn't as nice to deal with.
int[][] jaggedArray = new int[3][];
// initialize before using or else you'll get an error
jaggedArray[0] = new int[5];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[2];
// populate them like this:
jaggedArray[0] = new int[] { 1, 3, 5, 7, 9 };
jaggedArray[1] = new int[] { 0, 2, 4, 6 };
jaggedArray[2] = new int[] { 11, 22 };
See more here: http://msdn.microsoft.com/en-us/library/2s05feca.aspx

Can an array reference 2 different arrays

Lets say I have
int[] arraySegment1 = new int[10];
int[] arraySegment2 = new int[10];
Is there anyway to pass them into a one dimensional array by reference?
int[] array = new int[21];
//Could I now make the arraySegment1 be passed in array[0] - array[10] by reference?
//And arraySegment2 in array[11] - array[21] passed by reference?
//Then when executing:
array[0] = 10000000;
System.Console.WriteLine(arraySegment1[0]);
//It should display 10000000
//By putting the arraySegment1 as reference in the one dimensional array: array?
Checkout the Array.Copy method which allows you to copy segments of arrays to a destination array:
int[] arraySegment1 = new int[10];
int[] arraySegment2 = new int[10];
// TODO: populate the arraySegment1 and arraySegment2 with some values
int[] array = new int[20];
Array.Copy(arraySegment1, 0, array, 0, arraySegment1.Length);
Array.Copy(arraySegment2, 0, array, arraySegment1.Length, arraySegment2.Length);
Also 20 is enough of a Length for the resulting array, not 21 if the 2 source arrays are 10 each.
Try this one..
int[] arraySegment1 = new int[10];
int[] arraySegment2 = new int[10];
int[] array = new int[21];
arraySegment1.CopyTo(array,0);
arraySegment2.CopyTo(array,(arraySegment1.Length));
No. It's not possible with standart arrays. But with generics you can do something like this:
int[] arraySegment1 = new int[10];
int[] arraySegment2 = new int[10];
// populate arrays
List<int[]> lists = new List<int[]>();
lists.Add(arraySegment1);
lists.Add(arraySegment2);
lists[0][0] = 100000;
System.Console.WriteLine(arraySegment1[0]); // then it will display 100000
you typing wrong object
change the arraySegment1 in the write line to be array
System.Console.WriteLine(array[0]);

How do I get 2 similar arrays without one affecting the other

I am trying to do 2 different sorting algorithms on 2 exactly similar arrays (numbers and numbers2) that are generated through the Random class. I declare my 2 arrays and fill them with Random.NextBytes.
After that I do my first algorithm on numbers and then my second sorts on numbers2.
But I notice that numbers2 just seems to be a pointer to numbers because by the time I want to sort numbers2 it is already sorted.
How do I fill numbers2 with exactly the same numbers as numbers? Do I need to do it by hand with a for loop? Thank you!
class FillArray
{
public byte[] numbers;
public byte[] numbers2;
//instantiate MS Random object
Random Generator = new Random();
//Constructor which takes array size
public FillArray(int amountx)
{
numbers = new byte[amountx]
Generator.NextBytes(numbers);
numbers2 = new byte[amountx];
numbers2 = numbers;
amount = amountx;
}
Arrays are reference types, so if you want to clone the array you'll need to copy it via Array.Copy.
int[] first = new int[] { 1, 2, 3, 4, 5 };
int[] second = new int[first.Length];
Array.Copy( first, second, first.Length );
first[0] = 10;
// prints 10
Console.WriteLine( first[0] );
// prints 1
Console.WriteLine( second[0] );
You can also use Array.CopyTo. If you don't have a pre-existing array you can use the Clone() method as well to create a new one with shallow copies of all elements.
try
numbers2 = (byte[])numbers.Clone();
instead of
numbers2 = new byte[amountx];
numbers2 = numbers;
use Array.Copy method: Array.Copy Method
int[] source = new int[5];
source[0] = 1;
source[1] = 2;
source[2] = 3;
source[3] = 4;
source[4] = 5;
int[] target = new int[5];
Array.Copy(source, target, 5);
You are assigning the reference for numbers to numbers2 instead of the values. Try this:
public FillArray(int amountx)
{
numbers = new byte[amountx]
Generator.NextBytes(numbers);
numbers2 = new byte[amountx];
Array.Copy(numbers, numbers2, amountx);
amount = amountx;
}
As Ed says, arrays are reference types. Your error is below:
public FillArray(int amountx)
{
numbers = new byte[amountx]
Generator.NextBytes(numbers);
numbers2 = new byte[amountx];
numbers2 = numbers; // this line is why the arrays are the same
amount = amountx;
}
However, I have a different solution than the other 2 presented. If you include the System.Linq namespace, you can use .ToList() and .ToArray():
public FillArray(int amountx)
{
numbers = new byte[amountx]
Generator.NextBytes(numbers);
numbers2 = numbers.ToList().ToArray();
amount = amountx;
}
You will then have 2 separate copies of the array to sort independently.
Since arrays are reference types, you will need to create a clone of the array:
class FillArray
{
public byte[] numbers;
public byte[] numbers2;
//instantiate MS Random object
Random Generator = new Random();
//Constructor which takes array size
public FillArray(int amountx)
{
numbers = new byte[amountx]
Generator.NextBytes(numbers);
numbers2 = new byte[amountx];
// Array Copy solution
Array.CopyTo(numbers2, 0);
// Or a LINQ solution
numbers2 = numbers.ToArray();
// Or a Clone solution
numbers2 = (byte[])numbers.Clone();
amount = amountx;
}
}

How can I declare a two dimensional string array?

string[][] Tablero = new string[3][3];
I need to have a 3x3 array arrangement to save information to. How do I declare this in C#?
string[,] Tablero = new string[3,3];
You can also instantiate it in the same line with array initializer syntax as follows:
string[,] Tablero = new string[3, 3] {{"a","b","c"},
{"d","e","f"},
{"g","h","i"} };
You probably want this:
string[,] Tablero = new string[3,3];
This will create you a matrix-like array where all rows have the same length.
The array in your sample is a so-called jagged array, i.e. an array of arrays where the elements can be of different size. A jagged array would have to be created in a different way:
string[][] Tablero = new string[3][];
for (int i = 0; i < Tablero.GetLength(0); i++)
{
Tablero[i] = new string[3];
}
You can also use initializers to fill the array elements with data:
string[,] Tablero = new string[,]
{
{"1.1", "1.2", "1.3"},
{"2.1", "2.2", "2.3"},
{"3.1", "3.2", "3.3"}
};
And in case of a jagged array:
string[][] Tablero = new string[][]
{
new string[] {"1.1", "1.2"},
new string[] {"2.1", "2.2", "2.3", "2.4"},
new string[] {"3.1", "3.2", "3.3"}
};
You just declared a jagged array. Such kind of arrays can have different sizes for all dimensions. For example:
string[][] jaggedStrings = {
new string[] {"x","y","z"},
new string[] {"x","y"},
new string[] {"x"}
};
In your case you need regular array. See answers above.
More about jagged arrays
I assume you're looking for this:
string[,] Tablero = new string[3,3];
The syntax for a jagged array is:
string[][] Tablero = new string[3][];
for (int ix = 0; ix < 3; ++ix) {
Tablero[ix] = new string[3];
}
There are 2 types of multidimensional arrays in C#, called Multidimensional and Jagged.
For multidimensional you can by:
string[,] multi = new string[3, 3];
For jagged array you have to write a bit more code:
string[][] jagged = new string[3][];
for (int i = 0; i < jagged.Length; i++)
{
jagged[i] = new string[3];
}
In short jagged array is both faster and has intuitive syntax. For more information see: this Stackoverflow question
try this :
string[,] myArray = new string[3,3];
have a look on http://msdn.microsoft.com/en-us/library/2yd9wwz4.aspx
string[,] Tablero = new string[3,3];
string[][] is not a two-dimensional array, it's an array of arrays (a jagged array). That's something different.
To declare a two-dimensional array, use this syntax:
string[,] tablero = new string[3, 3];
If you really want a jagged array, you need to initialize it like this:
string[][] tablero = new string[][] { new string[3],
new string[3],
new string[3] };
A 3x3 (multidimensional) array can also be initialized (you have already declared it) like this:
string[,] Tablero = {
{ "a", "b", "c" },
{ "d", "e", "f" },
{ "g", "h", "i"}
};
When you are trying to create a multi-dimensional array all you need to do is add a comma to the declaration like so:
string[,] tablero = new string[3,3].
you can also write the code below.
Array lbl_array = Array.CreateInstance(typeof(string), i, j);
where 'i' is the number of rows and 'j' is the number of columns.
using the 'typeof(..)' method you can choose the type of your array i.e. int, string, double
There are many examples on working with arrays in C# here.
I hope this helps.
Thanks,
Damian

Categories

Resources