collection of two dimensional arrays in c# - c#

I'm new in C# and i was wondering if it is possible to store two dimensional arrays in a List or Observable Collection like this : ObservableCollection<double[,]> TwoDarray = new ObservableCollection<double[,]>(); and access each List element(the arrays in our case) with an index which points to specific elements(arrays) of the List.For example i want to plot some data from a custom class and i want to make a combobox which you can select and plot previous inputs if the user wants to plot previous inputs.

If you want to use the multidimensional array you mentioned in your post
double[,]
then you can create a list of those objects
Like:
List<double[,]> TwoDarray = new List<double[,]>();
Then to add one to the array you just use the list .add method
TwoDarray.add(new double[,]);
To access your new array you can simply use your
var x = TwoDarray[0];

Are you looking for something like this?
List<int[,]> myList = new List<int[,]>();
myList.Add(new int[,] {{1, 2}});
myList.Add(new int[,] {{3, 4}});
myList.Add(new int[,] {{5, 6}});
Console.WriteLine(myList[0][0, 0]); // Output: 1
Console.WriteLine(myList[2][0, 1]); // Output: 6

Related

c# - How to create 2D array with unknown number of rows, but known number of columns?

I am trying to create 2-dimensional array of ints with two columns, but an unknown amount of rows. I know that in order to create the 2D array itself I do the following:
List<List<int>> myList = new List<List<int>>();
But how do I modify this to specify the number of columns? And how would I add a row to this array?
You could use a List of int arrays. The List would represent the rows, and each int array in the List would be one row. The length of each array would equal the amount of columns.
List<int[]> rows = new List<int[]>();
int[] row = new int[2];
row[0] = 100;
row[1] = 200;
rows.Add(row);
As long as each int array is length two (int[] row = new int[2]), all rows will have two columns. The List can have any number of int arrays added to it in this way.
There is no way to create 2D array (or any other sort of array) with unknown number of elements. Once you initialize it you have to provide number of elements.
The syntax for multidimensional array is the following:
var arr = new int[k, l, n,...]
You can create so called jagged array, i.e. array of arrays and initialize it in the cycle. You will still need to initialize it with a number of subarrays and then fill with those subarrays of given lengths:
var arr = new int[][n];
for (int i = 0; i < arr.Length; i++)
{
arr[i] = new int[subArrayLength];
}
What you actually do is List of Lists which can have any number of "rows" of any length. You can add new list of specific length to an outer list by List method Add() and the same way you can add an element to any of inner List.
So basically to add a "row" you would need the following:
List<List<int>> table = new List<List<int>>();
table.Add(Enumerable.Repeat(defaultValue, numberOfColumns).ToList());
To add a column you would need something like this:
foreach (var row in table)
{
row.Add(defaultValue);
}
It seems that you want to simulate table structure - for that I would suggest to create a class to incapsulate table logic from above inside so that any addition of row will cause addition of outer List of current numberOfColumns size and addition of column will cause addition of an element to all outer lists.
However if you need a fixed number of columns the best alternative you can use is to declare a new class with your columns mapped to the properties of the class and then simply declare a List like it is described in the following answer as #shash678 pointed
Original answer: Consider using a List<Tuple<int, int>>.
Explanation: To begin with, an int[] is not a List<>. From the spirit of your question you seem to have the need to group several units of data together with a finite size, like a records in a table. You could decide to create a POCO with a more descriptive name (which would increase code readability and help with semantics), use an array of fixed size, or use a Tuple. Since there is no mention as to the need for mutability, and the size of the inner "array" will be fixed, I would suggest a Tuple. Through type safety you will ensure that the size and shape of each new object added to the list of Tuples is correct.
Your fist and second questions would be taken care, as far as the 3rd, see: Tuple Pair
e.g. list.Add(Tuple.Create<int,int>(1,1));
I feel like these answers are leading you down a bad path. When learning how to program, you should also consider best practices. In this case your code is what you should use. If you can avoid setting explicit array size, you should(In my opinion). List were create for this purpose. This sample app explains how to use the list correctly in this scenario. My personal opinion is to avoid using arrays if you can.
int someNumberOfRow = 10;//This is just for testing purposes.
Random random = new Random();//This is just for testing purposes.
List<List<int>> myList = new List<List<int>>();
//add two elements to the an arraylist<int> then add this arraylist to myList arraylist
for(int i = 0; i < someNumberOfRow; i++)
{
//Create inner list and add two ints to it.
List<int> innerList = new List<int>();
innerList.Add(random.Next());
innerList.Add(random.Next());
//Add the inner list to myList;
myList.Add(innerList);
}
//This prints myList
for(int i = 0; i < myList.Count; i++)
{
Console.WriteLine((i + 1) + ": " + myList[i][0] + " - " + myList[i][1]);
}
Console.WriteLine("\n\n");
//If the app may scale in the future, I suggest you use an approach similar to this
foreach(List<int> sublist in myList)
{
foreach(int columns in sublist)
{
Console.Write(columns + " ");
}
Console.WriteLine();
}
Console.ReadLine();

c# add new item to existing string[,] Array [duplicate]

This question already has answers here:
How to resize multidimensional (2D) array in C#?
(7 answers)
Closed 5 years ago.
I'm trying to use a multidimentional string array.
I can easily create it:
string[,] array = new string[,]
{
{"AA", "AB"},
{"AC", "AD"},
};
no issue here.
The idea is to add some more items after.
The assumption is that my array can be extended for many "rows" but just two "columns".
I've tried to do this:
array[0,0] = "AE";
array[0,1] = "AF";
but this does not seem to work. Why?
Also is there any way to add (concatenate/join?) e.g. in one go:
new string[,] { {"AE", "AF"} }
or
array[i,???] = {"AE", "AF"}
where i can be variable (e.g. to the last position) and the columns wouldn't have to be defined (based on 2 columns defined in the array)
this could add the new item into the existing array (at 3rd position)?
The string[,] is a very good solution to set up your items manually, but if you have external data that requires to be added to the array, I couldn't find any example it on any other posts.
Can someone help?
Thanks.
Regards,
you need a datastructure that can grow ( and shrink )
try :-
var array = new List<string[]> {new[] {"AE", "AF"}, new []{"A", "B"}};
and then
array.Add(new []{"XY", "AB"});
and you can access it like :-
Console.WriteLine(array[0][0]);
array[0][0] = "BB";
Console.WriteLine(array[0][0]);
If you like array initialization syntax, you can do that first and convert it to a list like :-
var initial = new[,] {{"H", "I"}, {"R", "V"}};
var array = Enumerable.Range(0, initial.GetUpperBound(0) + 1)
.Select(n => new[] {initial[n, 0], initial[n, 1]}).ToList();

C# arrays, how to create empty array?

I'm learning c#, with my primary language before now being php. I was wondering how (or if) you could create an empty array in c#.
In php, you can create an array, and then add any number of entries to it.
$multiples=array();
$multiples[] = 1;
$multiples[] = 2;
$multiples[] = 3;
In c#, I'm having trouble doing something similar:
int[] arraynums = new int[];
arraynums[] = 1;
arraynums[] = 2;
arraynums[] = 3;
Which gives the error "array creation must have array size or array initializer." If I don't know how many entries I want to make, how do I do this? Is there a way around this?
If you don't know the size in advance, use a List<T> instead of an array. An array, in C#, is a fixed size, and you must specify the size when creating it.
var arrayNums = new List<int>();
arrayNums.Add(1);
arrayNums.Add(2);
Once you've added items, you can extract them by index, just like you would with an array:
int secondNumber = arrayNums[1];
c# arrays have a static size.
int[] arraynums = new int[3];
or
int[] arraynums = {1, 2, 3}
if you want to use dynamic sized array, you should use ArrayList, or List.
I would recommend using a different collection such as a List<T> or a Dictionary<TKey, TValue>. Calling the collection in PHP an array is just a misnomer. An array is a continuous fixed size block of memory that contains only a single type and offers direct access by calculating the offset for a given index. The data type in PHP does none of these things.
Examples;
List<int> my_ints = new List<int>();
my_ints.Add(500);
Dictionary<string, int> ids = new Dictionary<string, int>();
ids.Add("Evan", 1);
int evansId = ids["Evan"];
Examples of when to use an array;
string[] lines = File.ReadAllLines(myPath);
for (int i = 0; i < lines.Length; i++)
// i perform better than other collections here!
Newer way, since .NET 4.6 / Core 1.0, in case somebody hits this:
System.Array.Empty<T>() method.
This is more efficient if called multiple times, as it's backed by a single static readonly array generated at compile time.
https://learn.microsoft.com/en-us/dotnet/api/system.array.empty
https://referencesource.microsoft.com/#mscorlib/system/array.cs,3079
Try this post: Dynamic array in C#. It has a couple of links in the first answer that show alternate ways of indexing data. In C#, there is no way of making dynamic arrays but those links show some workarounds.

Determining size of an array of arrays in C#?

I am creating an array of arrays such that:
var arrNewArray = new string[arrOldArray.Length][7];
arrOldArray is an array of arrays such that it's [X][4], meaning the length of the 1st array or "outside" array can change, but the length of the "inside" array is ALWAYS 4, or hold 4 strings ([0][1][2][3]).
Why won't the compiler accept my statement above?
Essentially, I'm trying to take arrOldArray and expand it, or add a few more "columns" by increasing the [4] in the old array to a [7] in the new array and then copy the contents over. Perhaps I'm not doing it the best/efficient way, so any guidance would be appreciated thanks.
I think you want a two dimensional array:
var arrNewArray = new string[arrOldArray.Length, 7];
You would access it like this: arrNewArray[x, y].
This is better than a jagged array, because it clearly communicates that the number of "columns" is the same for every row.
If you want to continue using a jagged array, you need to do it like this:
var arrNewArray = new string[arrOldArray.Length][];
for(int i = 0; i < arrOldArray.Length; ++i)
arrNewArray[i] = new string[7];
The reason for this convoluted way is: With a jagged array, each "row" can have a different number of "columns". A short-hand syntax for the case where each "row" has the same number of "columns" doesn't exist. That's why your code doesn't compile.
A jagged array is essential an array of arrays, so you need to create a new array instance for each "row" of the outer array and explicitly assign it. That's what the for loop is doing.
You can't use Array.Copy with jagged arrays. Each child-array is it's own instance and Array.Copy doesn't make a deep copy, it merely copies the references from one array to another. The effect would be, that both arrays would point to the same items and changing an item in one array would be seen from the other.
You are not creating the jagged array properly. The proper way is to create the first dimension of the jagged array and then loop through the items of the first dimension to create the nested arrays and copy the data from the old arrays. Here's an example:
int newSize = 7;
string[][] newArray = new string[oldArray.Length][];
for (int i = 0; i < oldArray.Length; i++)
{
newArray[i] = new string[newSize];
Array.Copy(oldArray[i], newArray[i], oldArray[i].Length);
}
You would be wanting
var arrNewArray = new string[arrOldArray.Length, 7];
var arrNewArray = new[] {new string[7]};//array of arrays
var arrNewArray = new string[arrOldArray.Length, 7];//two-dimensional array
Using Linq:
int[][] jaggedArray2 = new int[][]
{
new int[] {1,3,5,7,9},
new int[] {0,2,4,6},
new int[] {11,22}
};
int length = jaggedArray.Sum(a => a.Length);
I don't believe what you're asking is directly possible. Because the syntax that you are using is for a jagged array, and what you are doing is effectively asking it to create a multi-dimensional array.
The syntax is confusing since it reads like what you really want is a multi-dimensional array (although I'm aware that's not the case.)
I don't believe you could store your arrays in the newly allocated array either due to a size change. You would need to build a custom copy method to move the data into the larger array.

LINQ: transform an array [,] into array[]

I know this is kind of a dumb question, but does anyone have an elegant (or non-elegant) LINQ approach to transform a 2D array (object[,]) into a 1D array (object[]) comprised of the first dimension of the 2D array?
Example:
// I'd like to have the following array
object[,] dim2 = {{1,1},{2,2},{3,3}};
// converted into this kind of an array... :)
object[] dim1 = { 1, 2, 3 };
You claim that you want a 1D array (object[]) comprised of the first dimension of the 2D array, so I assume you are trying to select a subset of the original 2D array.
int[,] foo = new int[2, 3]
{
{1,2,3},
{4,5,6}
};
int[] first = Enumerable.Range(0, foo.GetLength(0))
.Select(i => foo[i, 0])
.ToArray();
// first == {1, 4}
#Elisha had posted an answer (didn't compile initially) also, which I was investigating this afternoon. I don't know why he deleted his answer, but I carried on with his code example until everything got worked out, and it also gives me what I need:
object[,] dim2 =
{{"ADP", "Australia"}, {"CDN", "Canada"}, {"USD", "United States"}};
object[] dim1 = dim2.Cast<object>().ToArray();
// dim1 = {"ADP", "CDN", "USD"}
This code compiles and returns the expected results. I glad about the .Cast(), and that I only needed the first dimension, not the second.
In general, for a collection of collections (instead of an array of arrays), you can do:
mainCollection.Select(subCollection => subCollection.First());

Categories

Resources