How to access Array[]? - c#

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

Related

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);
}
}

Is there any way to create or declare arrays automatically?

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;
}

Convert Ienumerable<int> to array and add to list C#

I have a simple code:
List<int[]> list = new List<int[]>();
for (int i = 0; i < x; i++)
{
var vec = vector.Skip(index).Take(width);
var v = vec.ToArray();
list.Add(v);
index = index + width;
}
string toDisplay = string.Join(Environment.NewLine, list);
MessageBox.Show(toDisplay);
This is vector:
int[] vector = new int[length];
Random z = new Random();
for (int i = 0; i < length; i++)
{
vector[i] = z.Next(-100, 100);
}
What I want to do is to slice my vector on smaller vectors and add them to list of int. Using my code I only get System.Int32[] in MessageBox. I know that maybe my code it's not the right way. I barely know C#.
How can I do this in other way?
Apparently you mean to slice the initial array into smaller chunks and display them in a single line. This can be done using Linq as follows.
var StringToDisplay
= String.Join(Environment.NewLine, list.Select(iList => String.Join(",", iList)));
List<int[]> list is a list of arrays, not numbers. Calling ToString() on an array uses Object.ToString() which returns the object's (array's) type.
If you want to display a list of pages, you should change your string construction code to work with the inner arrays. One option is to use LINQ :
var lines=from page in list
select string.Join(",", page);
string toDisplay = string.Join(Environment.NewLine, lines);
It's better to use StringBuilder though, to avoid generating a lot of temporary strings:
var builder=new StringBuilder();
foreach(var page in list)
{
builder.AppendLine(string.Join(",", page));
}
string toDisplay = builder.ToString();
If you want a list of numbers change the list type to List. You can also simplify the code by using AddRange, eg :
List<int> list = new List<int>();
for (int i = 0; i < x; i++)
{
var vec = vector.Skip(index).Take(width);
list.AddRange(vec);
index = index + width;
}
string toDisplay = string.Join(Environment.NewLine, lines);

How to get max/min of list of 2d array in c#

i have a list of 2d array like this:
static void Main(string[] args) {
List<int[,]> kidsL = new List<int[,]>();
int[,] square1 = new int[8, 8];
int[,] square2 = new int[8, 8];
int[,] square3 = new int[8, 8];
for (int i = 0; i < 8; i++)
for (int j = 0; j < 8; j++) {
square1[i, j] = 1;
square2[i, j] = 2;
square3[i, j] = 3;
}
kidsL.Add(square1);
kidsL.Add(square2);
kidsL.Add(square3);
Console.WriteLine();
Console.Read();
}
i want to determine sum of every array and find the maxamim/minimum one (in this case the maximum one is 192).
is there an easy way to do this or am I just going to have to loop through the old fashioned way?
Well, you can use the following code to get IEnumarable<int> from int[,]
var enumarable = from int item in square2
select item;
Also, you can use a Cast<int>() method in order to unwrap int[,] to IEnumarable<int>.
Then you can use Max() and Min() linq method.
var min = kidsL.Min(x => (from int item in x select item).Sum());
var max = kidsL.Max(x => (from int item in x select item).Sum());
// or
var min = kidsL.Min(x => x.Cast<int>().Sum())
or
var Max = (from int[,] array in kidsL
select (from int item in array select item).Sum())
.Max();
Update
from int[,] array in kidsL select (from int item in array select item).Sum() query returns you an IEnumarable<int> which contains sums. In order to have the index of max, you should cast IEnumarable to array or list using ToList or ToArray().
var sumList = (from int[,] array in kidsL
select(from int item in array select item).Sum())
.ToList();
var maxSum = sumList.Max();
var maxInd = sumList.IndexOf(maxSum);
sumList is a list of ints and contains sums. So then you can use Max method to get max sum and IndexOf to get index of the max.
Cast<int> method will flatten array to IEnumerable<int> which allows using LINQ.
var max = kidsL.Max(square => square.Cast<int>().Sum());
var min = kidsL.Min(square => square.Cast<int>().Sum());
You should also be aware of possible overflow which can happen if values and dimensions of the array would be large.
is there an easy way to do this or am I just going to have to loop through the old fashioned way?
Although the solution is concise it has the same efficiency as looping over every element of every array. But that's indeed is an easy way.

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