Is there any way to create or declare arrays automatically? - c#

The arrays depending on the user input.
for example:
int n;//from the user
for(i=1;i<=n;i++)
{
int[] arr + i = new int[5];
}
that means create 4 arrays (n=4):
array1
array2
array3
array4
how can I create? Is there any method?

It really depends on what exactly you are trying to do. For your example, you could try using a list of arrays. Whenever you need a new array, add a new array to the list.
List<int[]> arrays = new List<int[]>();
for(int i = 0; i < n; i++) {
arrays.Add(new int[5]);
}
To access a specific array in the list you can do
arrays[42]
To do something with all of the arrays, you can use a foreach loop:
foreach(var array in arrays) {
array[0] += 42;
}

Related

C# Pass 1D array from 2D array as function argument into function that accepts 1D array as argument [duplicate]

I'm looking to slice a two dimensional array in C#.
I have double[2,2] prices and want to retrieve the second row of this array. I've tried prices[1,], but I have a feeling it might be something else.
Thanks in advance.
There's no direct "slice" operation, but you can define an extension method like this:
public static IEnumerable<T> SliceRow<T>(this T[,] array, int row)
{
for (var i = 0; i < array.GetLength(0); i++)
{
yield return array[i, row];
}
}
double[,] prices = ...;
double[] secondRow = prices.SliceRow(1).ToArray();
Enumerable.Range(0, 2)
.Select(x => prices[1,x])
.ToArray();
The question is if you have a jagged or a multidimensional array... here's how to retrieve a value from either:
int[,] rectArray = new int[3,3]
{
{0,1,2}
{3,4,5}
{6,7,8}
};
int i = rectArray[2,2]; // i will be 8
int[][] jaggedArray = new int[3][3]
{
{0,1,2}
{3,4,5}
{6,7,8}
};
int i = jaggedArray[2][2]; //i will be 8
EDIT: Added to address the slice part...
To get an int array from one of these arrays you would have to loop and retrieve the values you're after. For example:
public IEnumerable<int> GetIntsFromArray(int[][] theArray) {
for(int i = 0; i<3; i++) {
yield return theArray[2][i]; // would return 6, 7 ,8
}
}

Populating an array with elements [duplicate]

Consider I have an Array,
int[] i = {1,2,3,4,5};
Here I have assigned values for it. But in my problem I get these values only at runtime.
How can I assign them to an array.
For example:
I get the max size of array from user and the values to them now how do I assign them to the array int [].
Or can I use anyother data types like ArrayList etc which I can cast to Int[] at the end?
Well, the easiest is to use List<T>:
List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);
list.Add(5);
int[] arr = list.ToArray();
Otherwise, you need to allocate an array of suitable size, and set via the indexer.
int[] arr = new int[5];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;
This second approach is not useful if you can't predict the size of the array, as it is expensive to reallocate the array every time you add an item; a List<T> uses a doubling strategy to minimize the reallocations required.
You mean?
int[] array = { 1, 2, 3, 4, 5 };
array = new int[] { 1, 3, 5, 7, 9 };
array = new int[] { 100, 53, 25, 787, 39 };
array = new int[] { 100, 53, 25, 787, 39, 500 };
Use List<int> and then call ToArray() on it at the end to create an array. But do you really need an array? It's generally easier to work with the other collection types. As Eric Lippert wrote, "arrays considered somewhat harmful".
You can do it explicitly though, like this:
using System;
public class Test
{
static void Main()
{
int size = ReadInt32FromConsole("Please enter array size");
int[] array = new int[size];
for (int i=0; i < size; i++)
{
array[i] = ReadInt32FromConsole("Please enter element " + i);
}
Console.WriteLine("Finished:");
foreach (int i in array)
{
Console.WriteLine(i);
}
}
static int ReadInt32FromConsole(string message)
{
Console.Write(message);
Console.Write(": ");
string line = Console.ReadLine();
// Include error checking in real code!
return int.Parse(line);
}
}
If you want an array, whose size varies during the execution, then you should use another data structure. A generic List will do. Then, you can dynamically add elements to it.
Edit: Marc posted his answer while I was writing mine. This was exactly what I meant.
You could just use the below line instead of calling a separate function:
using System;
public class Test
{
static void Main()
{
Console.WriteLine("Please enter array size");
int size = Convert.ToInt32(Console.ReadLine());
int[] array = new int[size];
for (int i=0; i < size; i++)
{
Console.WriteLine("Please enter element " + i);
array[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Finished:");
foreach (int i in array)
{
Console.WriteLine(i);
}
}

How to access Array[]?

Given the following code:
List<int> Data = new List<int>();
Data.Add(1);
Data.Add(2);
Array[] tmp = new Array[Data.Count];
tmp[0] = Data.ToString().ToArray();
How to access the Data array in tmp[0]?
I have try tmp[0,0] or tmp[0].Data[0] but it doesn't work and gives me an error.
simple is can I add array to array onedimesion? if can how?
Just write
Array tmp;
tmp = Data.ToArray();
for(int x = 0; x < tmp.Length; x++)
Console.WriteLine(tmp.GetValue(x));
However I recommend to stick at using a strong typed List
Going deeper along this slippery path you could create an Array of Array (oh boy this start to get confusing)
// Create an array of two Array
Array[] tmp = new Array[Data.Count];
// First array set to the integer array
tmp[0] = Data.ToArray();
// Second array of strings
tmp[1] = new string[5];
// Set first element of the second array to a string
tmp[1].SetValue("Steve", 0);
Again, forget this approach and use more advanced collection classes like
Dictionary
Hashset
Tuple
If you want to access your data a a specific position just use
Data[Index]
if you realy want to use a array you can do
int[] array = Data.ToArray();
Must do like this.
List<int> Data = new List<int>();
Data.Add(1);
Data.Add(2);
int[] tmp = Data.ToArray();
Simply you can use
var array=Data.ToArray();
and if you want to add new item in array you might want to resize it first using
Array.Resize(ref array, array.Count() + 1);
array[array.Count()]=//your items here..
When adding. deleting use List<T>:
List<int> Data = new List<int>();
// Add item after item
Data.Add(1);
Data.Add(2);
// Add whole range of items, e.g. an array
Data.AddRange(new int[] {3, 4, 5});
int v = Data[0];
Data[0] = v + 10;
Console.Write(String.Join(", ", Data));
Finally, when you to have an array
int[] tmp = Data.ToArray();
// you still can read an item
int x = tmp[0];
// and write it
tmp[0] = x - 10;
But remember, you can't do tmp.Add() or tmp.RemoveAt()

initializing multi-dim string arrays

Stuck here trying to initialize an array (c#) using a loop. The number of rows will change depending. I need to get back two values that I am calculating earlier in the program startweek, and endweek. Lots of examples on building int arrays using loops but nothing I can find re dynamic strings and multi dim arrays.
Thanks
how do I set the values for col1 in string[,] arrayWeeks = new string[numWeeks, col1]; Is that clearer?
(Thanks for the clarification.) You can do a multidimensional initializer like so:
string[,] arrayWeeks = new string[,] { { "1", "2" }, { "3", "4" }, { "5", "6" }, { "7", "8" } };
Or, if your array is jagged:
string[][] arrayWeeks = new string[][]
{
new string[] {"1","2","3"},
new string[] {"4","5"},
new string[] {"6","7"},
new string[] {"8"}
};
If you're in a loop, I'm guessing you want jagged. And instead of initializing with values, you may want to call arrayWeeks[x] = new string[y]; where x is the row you're adding and y is the number of elements in that row. Then you can set each value: arrayWeeks[x][i] = ... where you are setting the ith element in the row. Your initial declaration of the array would be string[][] arrayWeeks = new string[numRows][];
So, to summarize, you probably want something that looks like this:
int numRows = 2;
string[][] arrayWeeks = new string[numRows][];
arrayWeeks[0] = new string[2];
arrayWeeks[0][0] = "hi";
arrayWeeks[0][1] = "bye";
arrayWeeks[1] = new string[1];
arrayWeeks[1][0] = "aloha";
But, obviously, within your loop.
There are two types of what you might call "multidimensional" arrays in C#. There are genuine multidimensional arrays:
string[,] array = new string[4, 4];
array[0, 0] = "Hello, world!";
// etc.
There are also jagged arrays. A jagged array an array whose elements are also arrays. The "rows" in a jagged array can be of different lengths. An important note with jagged arrays is that you have to manually initialize the "rows":
string[][] array = new string[4][];
for(int i = 0; i < 4; i++) {
array[i] = new string[4];
}
array[0][0] = "Hello, world!";
If the number of rows change depending on some factor (not fixed), it would be better to use a container, such as a List (see list on the MSDN). You can nest a list within a list to create a multi-dimensional list.
Late to the conversation, but here is a jagged array example when you setting the size and data dynamically:
// rowCount from runtime data
stringArray = new string[rowCount][];
for (int index = 0; index < rowCount; index++)
{
// columnCount from runtime data
stringArray[index] = new string[columnCount];
for (int index2 = 0; index2 < columnCount; index2++)
{
// value from runtime data
stringArray[index][index2] = value;
}
}

Defining Dynamic Array

How can I define a dynamic array in C#?
C# doesn't provide dynamic arrays. Instead, it offers List class which works the same way.
To use lists, write at the top of your file:
using System.Collections.Generic;
And where you want to make use of a list, write (example for strings):
List<string> mylist = new List<string>();
mylist.Add("First string in list");
Take a look at Array.Resize if you need to resize an array.
// Create and initialize a new string array.
String[] myArr = {"The", "quick", "brown", "fox", "jumps",
"over", "the", "lazy", "dog"};
// Resize the array to a bigger size (five elements larger).
Array.Resize(ref myArr, myArr.Length + 5);
// Resize the array to a smaller size (four elements).
Array.Resize(ref myArr, 4);
Alternatively you could use the List class as others have mentioned. Make sure you specify an initial size if you know it ahead of time to keep the list from having to resize itself underneath. See the remarks section of the initial size link.
List<string> dinosaurs = new List<string>(4);
Console.WriteLine("\nCapacity: {0}", dinosaurs.Capacity);
dinosaurs.Add("Tyrannosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Mamenchisaurus");
dinosaurs.Add("Deinonychus");
If you need the array from the List, you can use the ToArray() function on the list.
string[] dinos = dinosaurs.ToArray();
C# does provide dynamic arrays and dynamic array manipulation. The base of an array is dynamic and can be modified with a variable. You can find the array tutorial here (https://msdn.microsoft.com/en-us/library/aa288453%28v=vs.71%29.aspx). I have also included code that demonstrates an empty set array and a dynamic array that can be resized at run time.
class Program
{
static void Main(string[] args)
{
int x = Convert.ToInt32(Console.ReadLine());
int y = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(x);
{
int[] dynamicArray1 = { };//empty array
int[] numbers;//another way to declare a variable array as all arrays start as variable size
numbers = new int[x];//setting this array to an unknown variable (will be user input)
for (int tmpInt = 0; tmpInt < x; tmpInt++)//build up the first variable array (numbers)
{
numbers[tmpInt] = tmpInt;
}
Array.Resize(ref numbers,y);// resize to variable input
dynamicArray1 = numbers;//set the empty set array to the numbers array size
for (int z = 0; z < y; z++)//print to the new resize
{
Console.WriteLine(numbers[z].ToString());//print the numbers value
Console.WriteLine(dynamicArray1[z].ToString());//print the empty set value
}
}
Console.Write("Dynamic Arrays ");
var name = Console.ReadLine();
}
}
Actually you can have Dynamic Arrays in C# it's very simple.
keep in mind that the response to your question above is also correct you could declare a
List Generic
The way to Create a Dynamic Array would be to declare your Array for example
string[] dynamicArry1 = { };//notice I did not declare a size for the array
List<String> tmpList = new List<string>();
int i = 1;
for(int tmpInt = 0; tmpInt < 5; tmpInt++)
{
tmpList.Add("Testing, 1.0." + tmpInt + ", 200, 3.4" + tmpInt +"," + DateTime.Now.ToShortDateString());
//dynamicArry1[tmpInt] = new string[] { tmpList[tmpInt].ToCharArray() };
}
dynamicArry1 = tmpList.ToArray();
how about ArrayList ?
If I'm not wrong ArrayList is an implementation of dynamic arrays
Example of Defining Dynamic Array in C#:
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();
like so
int nSize = 17;
int[] arrn = new int[nSize];
nSize++;
arrn = new int[nSize];

Categories