Get one dimensionial array from a mutlidimensional array in c# - c#

I have a two dimensional array like this:
decimal[,] dataArray;
dataArray = new decimal[10, 20];
How can I get an onedimesional array that contains the values from one particular column?
Thanks.

There is no built-in API for slicing multidimensional arrays. Write a loop that goes through all rows, and harvests a specific column into a result array, or use LINQ to "fold" the loop:
var col = Enumerable.Range(0, 20).Select(r=>dataArray[3, r]).ToArray();

Related

how to get length of string [] []

I have 2D array of string defined as
string[][] input_data;
I can count the number of rows by input_data.GetLength(0)
but if I use input_data.GetLength(1) to get number of column, I always get
System.IndexOutOfRangeException was unhandled
Message=Index was outside the bounds of the array.
Source=mscorlib
StackTrace:
at System.Array.GetLength(Int32 dimension)
...
I also noticed that at debugging, when I hover my mouse on my array (after all the data has been inserted) it only shows the first value (number of row) like this: input_data| {string[18][]}, if I continue expand the array then it shows all the 18 row data with the column data, like this:
How do I get the number of column? (in this case it is 139)
What you posted is a jagged array, not a multi-dimensional array. It's a 1-D array that contains other arrays. There is no second dimension so you can't use data.GetLength(1). Each row can have a different number of columns.
You can get the minimum or maximum number of columns for each row with data.Max(r=>r.Length) or data.Min(r=>r.Length), eg:
var s=new string[][]{
new[] {"a","b"},
new[] {"a"}
};
Console.WriteLine("{0} {1}",s.Max(r=>r.Length),s.Min(r=>r.Length));
will print
2 1
To specify a multi-dimensional array, you need to use the [,] syntax:
var s=new string[,]{
{"a","b"},
{"c","d"},
{"e","f"}
};
Console.WriteLine("{0} {1}",s.GetLength(0),s.GetLength(1));
This will return :
3 2
GetLength(1) would work if you had a multidimensional array:
string[,] input_data = new string[27,139];
var columns = input_data.GetLength(1);
What you have now is a jagged array not a 2D array, so there is no guarantee that all items ('rows') have the same number of elements ('columns').
However in case you can't use multidimensional array for some reason and you are sure that the input will be that way you can use the length of the first element input_data[0].Length
I think you are confusing an array of arrays and a multi dimentional array, run this code :
string[][] array_of_arrays = new string[5][];
Console.WriteLine(array_of_arrays.Length);
array_of_arrays[0] = new string[5];
array_of_arrays[1] = new string[6];
Console.WriteLine(array_of_arrays[0].Length);
Console.WriteLine(array_of_arrays[1].Length);
string[,] multi_d_array = new string[4,2];
Console.WriteLine(multi_d_array.GetLength(0));
Console.WriteLine(multi_d_array.GetLength(1));
This is a jagged array. You can get the first dimensions size as 'input_data.GetLength(0)' and second dimension size as 'input_data.GetLength(1)'. Try it
Example:
string[,] input_data = new string[5,12];
var column1 = input_data.GetLength(0);
var column2 = input_data.GetLength(1);

Get a sub array using array of indexes in one step

In C#, given an array of integers that represents indexes of an array of items, is there a way to get a sub-array of the array of items that correspond to indexes in one step?
int[] indexesArray = {0,2,4,1};
string[] itemsArray = {"hi", "ciao", "yo"," hey","hello"};
string[] result = builtinMagic(itemsArray, indexesArray);
You can simply Select the index from the indexesArray and then get the item at that specific index:
string[] result = indexesArray.Select(idx => itemsArray[idx]).ToArray();

How to Convert 2D List to 2D Array in C#

I have the following C# List:
List<Response> listAllData = new List<Response>();
listAllData.Add(new Response() {
strId = propResponse.strId,
strName = propResponse.strName
});
And then I am converting it to an array as such:
object[] array2 = listAllData.ToArray();
But when I'm trying to write data to a range using:
rngValues.Value = array2;
I'm getting an error
Exception from HRESULT: 0x800A03EC
I am (reasonably) certain this is b/c the resulting array2 is not actually a 2D multidimensional array, but instead an array-of-arrays.
So my question is... How do I get my listAllData into a 2D array?
It is not a "jagged array" meaning there are always 2 elements in each entry.
resulting array2 is not actually a 2D multidimensional array, but instead an array-of-arrays.
No, it's a 1-D array of Response objects. If you want it in a 2-D array of objects (where the row is the two string properties from the source object) you'll have to build a loop (Linq does not support 2-D arrays):
object[,] array2 = new object[listAllData.Count,2];
for(int i = 0; i < listAllData.Count; i++)
{
array2[i,0] = listAllData[i].strId;
array2[i,1] = listAllData[i].strName;
}

Converting <T>[][] to <T>[] by extracting 1 element from the inner array

Is there a potential 1 liner that allows me to create a new 1 dimensional array from a certain index of the inner array of the 2D?
Example take the first element of each inner array:
double[][] array2D = new double[10][] // with inner arrays say double[5]
double[] array1D = new double[10];
for (int i=0; i<array2D.Length; i++)
{
array1D[i] = array2D[i][0];
}
I'd just use LINQ. That won't "avoid loops" in terms of execution, but it'll avoid a loop in your source code:
// 1dArray isn't a valid identifier...
var singleArray = jaggedArray.Select(x => x[0]).ToArray();
Note that this relies on it being a jagged array (an array of arrays). It will not do what you expect for true multi-dimensional (rectangular) arrays.
Or slightly more efficiently:
var singleArray = Array.ConvertAll(jaggedArray, x => x[0]);
That's more efficient because it knows the output size to start with, and builds the array directly - but it's a bit less idiomatic than using LINQ these days (which is more generally applicable to all sequences, not just arrays).

adding two int array

I have to add two int[] array in which a mian int[] array is intially vacant. I want to add the elements of another array in the main array . In the Main array, there would be more addtion that would be added in the last postion of the main array.
I have an array as -
var planetNotInRange = new int[7] ;
if(planetSign.Contains(tempFrind))
{
var result = planetSign.Select((b, k) => b.Equals(tempFrind) ? k : -1)
.Where(k => k != -1).ToArray();
// Here I want to add this result Array in to the planetNotInRange array,
// when ever there is some value in the result array.
}
this is in loop will give a number of array of integers. Now I want to concat in PLanetInRange Array one after other.
It sounds like you shouldn't have an array to start with, if you want to add elements to it. Once an array has been created, its size is fixed.
Use a List<int> instead, and you can use
list.AddRange(array);
I'd usually advise using lists (and other collection types) over arrays anyway. Arrays are useful, obviously, but they're somewhat more primitive and low-level than other collections.

Categories