C# Notes: Arrays

1. Creating an array instance

Arrays are reference types, regardless of the type of their elements. This means that an array variable refers to a contiguous block of memory holding the array elements on the heap.

This rule applies regardless of the type of the data items in the array. Even if the array contains a value type such as int, the memory will still be allocated on the heap.

Creating arrays follows the same pattern as creating a class instance: when you declare an array variable, you do not declare its size and no memory is allocated (other than to hold the reference on the stack). The array is given memory only when the instance is created, and this is also the point at which you specify the size of the array.

Syntax: int[] a = new int[4];

In other words, C# arrays are dynamically allocated !

2. Array syntax

Some correct codes:

int[] a = {1, 2, 4}
int[] b = new int[3] {1, 2, 4};
int[] c = new int[3];
int[] d = new int[] {1, 3, 5, 7}

var d = { 1, 4, 5, "adsfjkdf" } // the compiler regard this as an array of strings
var e = new[] {
    new {Name = "John", Age = 17},
    new {Name = "Wenke", Age = 20},
    new {Name = "youwen", Age = 19}
} // The fields in the anonymous types must be the same for each element of the array.

3. Passing and returning arrays

It is important to remember that arrays are reference types. The modifications on an array parameter are visible for every reference of the array, including the actual argument.

For example, a bubble sort in C#

public int[] bubble(int[] list)
{
    int temp = 0;
    for (int i = list.Length; i > 0; i--)
    {
        for (int j = 0; j < i - 1; j++)
        {
            if (list[j] > list[j + 1])
            {
                temp = list[j];
                list[j] = list[j + 1];
                list[j + 1] = temp;
            }
        }
    }
    return list;
}

4. Copying arrays

Arrays are reference types(In fact, each array is an instance of class System.Array), thus when you copy an array variable, you actually end up with two references to the same array instance. This is called “shallow copy”

If you want to copy the content of an array, you must allocate another array of the same size. Then you can either copy the array element-by-element, or call System.Array.CopyTo() member method.

int[] a = {1, 2, 3, 4};
int[] b = new int[a.Length];
a.CopyTo(b);

5. Multidimensional Arrays

In C#, there does exist the concept of multidimensional arrays.

For example, initializing a matrix of 4 rows and 40 columns

int[,] items = new int[4, 40];

Multidimensional arrays can consume a lot of memory. If the application uses only some of thedata in each column, allocating memory for unused elements is a waste. In this scenario, you can use a jagged array.

Attention: jagged array and multidimensional array are different data types!

class ArrayTest
{
    static void Main()
    {
        // Declare the array of two elements:
        int[][] arr = new int[2][];

        // Initialize the elements:
        arr[0] = new int[5] { 1, 3, 5, 7, 9 };
        arr[1] = new int[4] { 2, 4, 6, 8 };

        // Display the array elements:
        for (int i = 0; i < arr.Length; i++)
        {
            System.Console.Write("Element({0}): ", i);

            for (int j = 0; j < arr[i].Length; j++)
            {
                System.Console.Write("{0}{1}", arr[i][j], j == (arr[i].Length - 1) ? "" : " ");
            }
            System.Console.WriteLine();
        }
        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
/* Output:
    Element(0): 1 3 5 7 9
    Element(1): 2 4 6 8
*/
时间: 2024-12-28 18:04:19

C# Notes: Arrays的相关文章

【DataStructure】Some useful methods for arrays

Last night it took me about two hours to learn arrays. For the sake of less time, I did not put emphaises on the practice question, just now when reading the book, I found that some methods referred to arrays are so beneficial to us. So in here make

Core Java Volume I — 3.10. Arrays

3.10. ArraysAn array is a data structure that stores a collection of values of the same type. You access each individual value through an integer index. For example, if a is an array of integers, then a[i] is the ith integer in the array.Declare an a

[LeetCode] 349 Intersection of Two Arrays &amp; 350 Intersection of Two Arrays II

这两道题都是求两个数组之间的重复元素,因此把它们放在一起. 原题地址: 349 Intersection of Two Arrays :https://leetcode.com/problems/intersection-of-two-arrays/description/ 350 Intersection of Two Arrays II:https://leetcode.com/problems/intersection-of-two-arrays-ii/description/ 题目&解法

Arrays工具类

Arraysd的静态方法能够方便的对数组进行操作,每个方法也加了注释 : 程序: import java.util.*;public class Array{        public static void main(String[] args){                int[]  arr={1,3,4,2};                System.out.println("排序前:");                printArray(arr);//打印原数组

350.求两个数组的交集 Intersection of Two Arrays II

Given two arrays, write a function to compute their intersection. Example:Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2]. Note: Each element in the result should appear as many times as it shows in both arrays. The result can be in any ord

ArrayList&amp;LinkedList&amp;Map&amp;Arrays

Java集合框架 1:集合接口 1.1:Collection接口 Collection接口是构造集合框架的基础.它声明所有类集合都将拥有的核心方法 Boolean add(Object obj) 将obj加入到调用类集合中,加入返回true 否则 返回 false Boolean addAll(Collection c) 将c中所有元素都加入到类集合中,都加入返回true否则 false Void clean() 从调用类集合中删除所有元素 Boolean contains(Object obj

LeetCode OJ 4. Median of Two Sorted Arrays

There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). Example 1: nums1 = [1, 3] nums2 = [2] The median is 2.0 Example 2: nums1 = [1,

leetcode----------------Median of Two Sorted Arrays

There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). 分析 这是一道非常经典的题.这题更通用的形式是,给定两个已经排序好的数组,找到两者所有元素中第 k 大的元素.O(m + n) 的解法比较直观,直接merge两个数组,然后

84. 从视图索引说Notes数据库(下)

作用和代价上文介绍了关系型数据库里的索引.Notes数据库里的索引隐藏在视图概念里(本文的讨论只针对Notes的视图索引,不包含全文索引.).开发人员创建的视图仅仅是存放在数据库里的一条设计文档,数据库引擎会依据它创建和更新索引.关系型数据库里的索引是从记录中抽取的数据排序而组成的数据结构(主要是B树),Notes视图的索引还包括未排序的列.计算值.分类.总计等等数据(数据结构仍然是B树,如果运气足够好的话,你会遇到Notes报出B-tree structure is invalid的错误).用