eTothEipiPlus1
eTothEipiPlus1

Reputation: 587

How to extract one column from a jagged array?

I have a jagged array which is basically just a matrix with m rows and n columns (I know I could have used a normal matrix but I read that matrix multiplication is faster using a jagged array).

I'd like to extract every row from only one column without using a for loop. How is this accomplished. Also, please explain the code because I found an answer that claims that the following should work but I cannot figure out how to adapt it to my situation.

object[] column = Enumerable.Range(0, myArray.GetLength(0))
                            .Select(rowNum => (object)myArray[daily.m, daily.n])
                            .ToArray(); 

Okay so the following answer doesn't seem to give me errors but now I'm running into another problem:

var selectedArray = myArray.Where(o => (o != null && o.Count() > daily.dependentVarIndex)).Select(o => o[daily.dependentVarIndex]).ToArray();
            Method1 m1 = new Method1(13);
            for (int i = 0; i < daily.m; i++)
            {
                m1.do(selectedArray[i]); //this give me an error
            }

How can I now index the object "selectedArray"? Note that I defined Method1, the fxn "do" earlier in my code.

Upvotes: 1

Views: 2209

Answers (2)

Margus
Margus

Reputation: 20058

Using lambda:

var jaggedArray = new int[5][];
jaggedArray[0] = new[] { 1, 2, 3 }; // 3 item array
jaggedArray[1] = new[] { 7, 6 };
jaggedArray[3] = new int[10]; // 10 item array of 0's

const int selectItem = 0;
var selectedArray = jaggedArray
    .Where(o => (o != null && o.Count() > selectItem))
    .Select(o => o[selectItem])
    .ToArray();

Following array should contain 3 items

[1, 7, 0]

Upvotes: 2

decPL
decPL

Reputation: 5402

int [][] jaggedArray = /* SNIP */

jaggedArray.Select(row => row.Length >= ZERO_INDEXED_COLUMN_NO + 1
                           ? (int?)row[ZERO_INDEXED_COLUMN_NO]
                           : null)
           .ToArray();

where ZERO_INDEXED_COLUMN_NO is the zero-indexed number of column you wish to retrieve. The result is an array of (int?) with a null value where a given row is to short to have the ZERO_INDEXED_COLUMN_NO entry.

Upvotes: 0

Related Questions