Get the number of rows that actually contain data in a two-dimensional array

When writing a program, I encountered the need to obtain the number of rows of data actually stored in a two-dimensional array. I saw that the array.Rank method was used to obtain the number of array rows in several blogs. This is the way to get the dimension, I posted the correct method I found below, it is very practical.

 

///  <summary> 
/// Get the number of rows that actually store data in the two-dimensional array
 ///  </summary>         
public  static List< int > GetHasValueRowIndex( string [,] arr)
{
    var hasValueRowIndex = new List<int>();
    for (var i = 0; i < arr.GetLength(0); i++)
    {
        for (var j = 0; j < arr.GetLength(1); j++)
        {
            if (!string.IsNullOrEmpty(arr[i, j]))
            {
                hasValueRowIndex.Add(i);
                break;
            }
        }
    }
    return hasValueRowIndex;
}

//Demo

string[,] a = new string[9, 3];
a[0, 0] = "a";
a[2, 0] = "b";
a[4, 0] = "c";
a[6, 0] = "d";
a[8, 0] = "e";

var arr = GetHasValueRowIndex(a);
Console.WriteLine("HasValue Row Count:" + arr.Count);
arr.ForEach(o => Console.WriteLine(o));
/*
 HasValue Row Count:5
 0
 2
 4
 6
 8
 */

 

int [,] array = new  int [,] {{ 1 , 2 , 3 },{ 4 , 5 , 6 },{ 7 , 8 , 9 },{ 10 , 11 , 12 }}; // define a 4 Two-dimensional array with row 3 columns 
int dimension= array.Rank; // Get the dimension of the array; the value is 2 
int row = arr.GetLength( 0 ); // Return the length of the first dimension (the so-called "row number") (The number of rows of all data is not the number of rows where the data is actually stored) 
int col = array.GetLength( 1 ); //Get the number of elements in the specified dimension, which is the number of columns here. (0 is the first dimension, 1 means the second dimension); the value is 3 
int col = array.GetUpperBound( 0 )+ 1 ; // Get the upper limit of the index of the specified dimension, adding a 1 is the total number, which is expressed here The number of rows of a two-dimensional array 
int num = array.Length; // Get the length of the entire two-dimensional array, that is, the number of all elements

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326497925&siteId=291194637