Monday, December 13, 2021

C# Multidimensional Array

 

C# Multidimensional Array

In this tutorial, we will learn about the multidimensional array in C# using the example of two-dimensional array.

In a multidimensional array, each element of the array is also an array. For example,

int[ , ] x = { { 1, 2 ,3}, { 3, 4, 5 } };

Here, x is a multidimensional array which has two elements: {1, 2, 3} and {3, 4, 5}. And, each element of the array is also an array with 3 elements.

A 2-dimensional array can be thought of as a table, which has x number of rows and y number of columns. Following is a 2-dimensional array, which contains 3 rows and 4 columns −

Two Dimensional Arrays in C#

Thus, every element in the array a is identified by an element name of the form a[ i , j ], where a is the name of the array, and i and j are the subscripts that uniquely identify each element in array a.

Two-Dimensional Array Declaration

Here's how we declare a 2D array in C#.

int[ , ] x = new int [3, 4];

Initializing Two-Dimensional Arrays

Multidimensional arrays may be initialized by specifying bracketed values for each row. The Following array is with 3 rows and each row has 4 columns.

int [,] a = new int [3,4] {
   {0, 1, 2, 3} ,   /*  initializers for row indexed by 0 */
   {4, 5, 6, 7} ,   /*  initializers for row indexed by 1 */
   {8, 9, 10, 11}   /*  initializers for row indexed by 2 */
};

Accessing Two-Dimensional Array Elements

An element in 2-dimensional array is accessed by using the subscripts. That is, row index and column index of the array. For example,

int[,] arr2d = new int[3,2]{ 
                                {1, 2}, 
                                {3, 4}, 
                                {5, 6} 
                            };

arr2d[0, 0]; //returns 1
arr2d[0, 1]; //returns 2
arr2d[1, 0]; //returns 3
arr2d[1, 1]; //returns 4
arr2d[2, 0]; //returns 5
arr2d[2, 1]; //returns 6
//arr2d[3, 0]; //throws run-time error as there is no 4th row
In the above example, the value of a two-dimensional array can 
be accessed by index no of row and column as [row index, column index].
So, [0, 0] returns the value of the first row and first column and [1, 1] returns the value from the second row and second column.
Change Array Elements

We can also change the elements of a two-dimensional array. To change the element, we simply assign a new value to that particular index. For example,

using System;

namespace MultiDArray {
  class Program {
    static void Main(string[] args) {

    int[ , ] numbers = {{2, 3}, {4, 5}};
 	 
     // old element
    Console.WriteLine("Old element at index [0, 0] : "+numbers[0, 0]);
 	 
      // assigning new value
    numbers[0, 0] = 222;
  	 
      // new element
    Console.WriteLine("New element at index [0, 0] : "+numbers[0, 0]);
    }
  }
}

Output

Old element at index [0, 0] : 2
New element at index [0, 0] : 222

In the above example, the initial value at index [0, 0] is 2. Notice the line,

// assigning new value
numbers[0, 0] = 222;

Here, we are assigning a new value 222 at index [0, 0]. Now, the value at index [0, 0] is changed from 2 to 222.


Iterating C# Array using Loop

using System;

namespace MultiDArray {
  class Program  {
    static void Main(string[] args)  {

      int[ , ] numbers = { {2, 3, 9}, {4, 5, 9} };
   	 
      for(int i = 0; i < numbers.GetLength(0); i++)  { 
        Console.Write("Row "+ i+": ");

        for(int j = 0; j < numbers.GetLength(1); j++)  { 
          Console.Write(numbers[i, j]+" ");
 
        }
        Console.WriteLine(); 
  
      }  
    }
  }
}

Output

Row 0: 2 3 9
Row 1: 4 5 9

In the above example, we have used a nested for loop to iterate through the elements of a 2D array. Here,

  • numbers.GetLength(0) - gives the number of rows in a 2D array
  • numbers.GetLength(1) - gives the number of elements in the row

Note: We can also create a 3D array. Technically, a 3D array is an array that has multiple two-dimensional arrays as its elements. For example,

int[ , , ] numbers = { { { 1, 3, 5 }, { 2, 4, 6 } },
                                 { { 2, 4, 9 }, { 5, 7, 11 } } };

Here, [ , , ] (2 commas) denotes the 3D array.

SQL With Ties Clause

 The WITH TIES allows you to return more rows with values that match the last row in the limited result set. Note that WITH TIES may cause more rows to be returned than you specify in the expression.

The selection of which the rows to return is nondeterministic.
This means that if you run the query again, without the underlying data changing, theoretically you could get a different set of three rows.
In practice, the row selection will depend on physical conditions like :

  • optimization choices
  • storage engine choices
  • data layout
  • etc...

If you actually run the query multiple times, as long as those physical conditions don’t change, there’s some likelihood you will keep getting the same results. But it is critical to understand the “physical data independence” principle from the relational model, and remember that at the logical level you do not have a guarantee for repeatable results. Without ordering specification, you should consider the order as being arbitrary, resulting in a nondeterministic row selection


If you want to use TOP WITH TIES you must use order by.

Create Table

CREATE TABLE [dbo].[Products](
[Id] [int] IDENTITY(1,1) NOT NULL,
[ProductName] [nvarchar](50) NULL,
[Price] [float] NULL) 
GO

The following illustrates the INSERT statement that inserts rows into an existing table

INSERT INTO [dbo].[Products] VALUES ('Bicycle 1' , 258.2)
INSERT INTO [dbo].[Products] VALUES ('Bicycle 2' , 265.3)
INSERT INTO [dbo].[Products] VALUES ('Bicycle 3' , 267.8)
INSERT INTO [dbo].[Products] VALUES ('Bicycle 4' , 268.9)
INSERT INTO [dbo].[Products] VALUES ('Bicycle 5' , 267.9)
INSERT INTO [dbo].[Products] VALUES ('Bicycle 6' , 267.9)
GO

then

SELECT TOP 4 WITH TIES ProductName, Price
FROM Products  ORDER BY Price

In this example, the two expensive product has a list price of 267.9. Because the statement used TOP WITH TIES, it returned one more products whose list prices are the same as the forth one.

here


If you run the normal top 4 then the result set will be 


select top 4 ProductName, Price FROM Products order by price




Note: In the above result we got first 4 rows, ordered by Prince in Descending Order, but we have one more row with same price i.e, the row with name Bicycle 6 and Price 267.9, but it didn’t came up, because we restricted our output to first four rows only. But this is not optimal, because most of the time in live applications we will be required to display the tied rows also.

So, to overcome the above problem, SQL Server introduces a clause known as With Ties clause. Now, let’s see our previous example using With Ties clause.


Popular Posts