Array

f:http://www.dotnetperls.com/array  


Array. A prism refracts light. As white light enters, it splits apart. It becomes an array of colors. Consider a string array—we can use strings for these colors.
Arrays are inside many things. An array has an element type. Its elements are accessed with an index. An array cannot be resized—it can only be replaced.
String arrays. We begin with string arrays. Square brackets are used for all arrays. The syntax is fairly simple, but we need to memorize it.

Note:All of these constructs are equivalent in the compiled code. Please choose the one you think is clearest.

Var:The var type is an implicitly-typed local variable. It is the same to the compiler as an explicit string array.

Tip:The fourth array allows us to test each value or insert logic as we assign it. This is sometimes useful.

Based on: .NET 4.6

C# program that initializes string arrays

class Program
{
    static void Main()
    {
	// String arrays with 3 elements:
	string[] arr1 = new string[] { "one", "two", "three" };
	string[] arr2 = { "one", "two", "three" };
	var arr3 = new string[] { "one", "two", "three" };

	string[] arr4 = new string[3];
	arr4[0] = "one";
	arr4[1] = "two";
	arr4[2] = "three";
    }
}


Int array, parameter.  Here is an int array that is passed as a parameter. The entire contents of the array are not copied—just the small reference.

Tip:We can think of an array as a class with a variable number of fields, each accessed with an index.

C# program that receives array parameter

using System;

class Program
{
    static void Main()
    {
	// Three-element array.
	int[] array = { -5, -6, -7 };
	// Pass array to Method.
	Console.WriteLine(Method(array));
    }

    /// <summary>
    /// Receive array parameter.
    /// </summary>
    static int Method(int[] array)
    {
	return array[0] * 2;
    }
}

Output

-10

Return.  We can return arrays from methods. In this example program, we allocate a two-element array of strings in Method(). Then, after assigning its elements, we return it.
C# program that returns array reference

using System;

class Program
{
    static void Main()
    {
	// Write array from Method.
	Console.WriteLine(string.Join(" ", Method()));
    }

    /// <summary>
    /// Return an array.
    /// </summary>
    static string[] Method()
    {
	string[] array = new string[2];
	array[0] = "THANK";
	array[1] = "YOU";
	return array;
    }
}

Output

THANK YOU

First.  The first element is at index 0. It can be accessed by using the indexer syntax, which has square brackets. We first ensure that it can be accessed in the array region.
C# program that gets first array element

using System;

class Program
{
    static void Main()
    {
	int[] array = new int[2]; // Create an array.
	array[0] = 10;
	array[1] = 20;

	Test(array);
	Test(null); // No output.
	Test(new int[0]); // No output.
    }

    static void Test(int[] array)
    {
	if (array != null &&
	    array.Length > 0)
	{
	    int first = array[0];
	    Console.WriteLine(first);
	}
    }
}

Output

10

Last.  The last element's offset is equal to the array Length minus one. Often we need to check against null, and that the Length is greater than zero, before accessing the last element.
C# program that gets last array element

using System;

class Program
{
    static void Main()
    {
	string[] arr = new string[]
	{
	    "cat",
	    "dog",
	    "panther",
	    "tiger"
	};
	// Get the last string element.
	Console.WriteLine(arr[arr.Length - 1]);
    }
}

Output

tiger

Foreach, for-loops.  Here we use a foreach loop and a for-loop to iterate over a string array. The length of this array is 2, so the valid indexes are 0 and 1.

Foreach:With this loop, no indexes are needed. The loop itself handles the indexes. This makes some code simpler.

C# program that uses for each, for-loops on array

using System;

class Program
{
    static void Main()
    {
	string[] array = new string[2];
	array[0] = "Socrates";
	array[1] = "Plato";
	for (int i = 0; i < array.Length; i++)
	{
	    // Get element by index.
	    string element = array[i];
	    Console.WriteLine(element);
	}
	Console.WriteLine(); // Write blank line.
	foreach (string element in array)
	{
	    // Cannot assign element in this loop.
	    Console.WriteLine(element);
	}
    }
}

Output

Socrates
Plato

Socrates
Plato

IndexOf.  The Array class has many helpful methods. We can use IndexOf, for example, to search an array by value. Here we find the index of the string "dog."

Warning:IndexOf methods return -1 when no element is found. This value often must be checked in an if-statement.

C# that uses Array.IndexOf

using System;

class Program
{
    static void Main()
    {
	string[] array = { "cat", "dog", "bird", "fish" };

	// The dog string is at index 1.
	int dogIndex = Array.IndexOf(array, "dog");
	Console.WriteLine(dogIndex);

	// There is no monkey string in the array.
	// ... So IndexOf returns -1.
	int monkeyIndex = Array.IndexOf(array, "monkey");
	Console.WriteLine(monkeyIndex);
    }
}

Output

1
-1

2D array.  The C# language offers two-dimensional and multidimensional arrays. We also loop over 2D arrays. We use them with enumerators. 2D Array
3D array.  If two dimension are not enough, try a three-dimensional array. Even further dimensions can be added. Multidimensional arrays are rarely ideal. 3D Array
Jagged array.  This is an array of arrays. It can be faster, or slower, than a 2D array based on usage. The memory required too varies. This depends on the shape of data. Jagged Array Jagged Array: Memory
Class, indexer.  We use arrays as fields (or properties) in classes. This is useful for storing values. In the Test class here, we have a string array field.

Elements:The second part of the Test class is a property accessor. It provides a clean way for external code to access the internal array.

Indexer:The final part of the Test class is called an Indexer. An indexer uses the this-keyword.

Class Indexer

Note:The indexer shown receives one parameter, an integer, and returns a value based on it.

C# that uses string array in class

class Program
{
    static void Main()
    {
	// Create new instance with string array.
	Test test = new Test();

	// Loop over elements with property.
	foreach (string element in test.Elements)
	{
	    System.Console.WriteLine(element);
	}
	// Get first string element.
	System.Console.WriteLine(test[0]);
    }
}

public class Test
{
    /// <summary>
    /// String array field instance.
    /// </summary>
    string[] _elements = { "one", "two", "three" };

    /// <summary>
    /// String array property getter.
    /// </summary>
    public string[] Elements
    {
	get { return _elements; }
    }

    /// <summary>
    /// String array indexer.
    /// </summary>
    public string this[int index]
    {
	get { return _elements[index]; }
    }
}

Output

one
two
three
one

Join, Split.  The string.Join() method receives a string array and combines the strings into one. And Split() separates strings that are joined together with a delimiter char.

Join:This example uses the Join method to combine the three string literals within the "elements" array.

Join

Split:Finally we invoke Split to change our joined string back into a string array. The two string arrays are separate in memory.

Split
C# that uses Join, Split

using System;

class Program
{
    static void Main()
    {
	string[] elements = { "cat", "dog", "fish" };
	Console.WriteLine(elements[0]);

	// ... Join strings into a single string.
	string joined = string.Join("|", elements);
	Console.WriteLine(joined);

	// ... Separate joined strings with Split.
	string[] separated = joined.Split('|');
	Console.WriteLine(separated[0]);
    }
}

Output

cat
cat|dog|fish
cat

String args.  When a C# program is started, an optional string array is received from the operating system. This array, args, contains string arguments. Main, Args

Start:Try creating a shortcut in Windows to your C# executable. The args array is empty when no arguments are passed.

Here:I added the argument string "hello world" to the command in the Windows shortcut. The two strings are received into the args array.

C# that uses args string array

using System;

class Program
{
    static void Main(string[] args)
    {
	// ... Loop over arguments passed to this program.
	foreach(string value in args)
	{
	    Console.WriteLine("Argument: {0}", value);
	}
	Console.ReadLine();
    }
}

Output

Argument: hello
Argument: world

Types.  Arrays can be of any type. We can have (for example) bool, byte, int or char arrays. And all these arrays can also be used as static fields or properties. They can be null. Bool Array Byte Array Char Array Enum Array Int Array
Types, null.  An array is a reference type (like a string) so it can be null. An array property often benefits from special-casing. We avoid returning null. Array: Null Array: Property, Avoid Null
Types, random.  We can use the Random NextBytes method to fill a byte array with random values. This does not require much custom code. Array: Random
Types, strings.  String arrays are different from other arrays. Strings are the only data type we declare with quoted values. Strings can be null. We often must convert these arrays. Convert Array, String
Initialize.  An array's elements can be initialized in many ways. Some of the syntax forms are complex. It is often easier to just to assign elements. Initialize: Initializer Syntax Initialize: Loops, Enumerable
Combine.  Suppose two arrays exist. We can combine them. Suppose a 2D array is present. We can flatten it into a single array. An array can operated upon in nearly any way imaginable. Combine Flatten
Methods.  The Array type introduces many methods. We use these methods to manipulate or test arrays and their elements. We use BinarySearch—this optimizes searching a sorted array. AsReadOnly BinarySearch Clear ConstrainedCopy ConvertAll Copy CreateInstance Exists Find FindIndex ForEach IndexOf LastIndexOf Resize Reverse Sort TrueForAll
Properties.  The most commonly used property on arrays is the Length property. With Length, we access a stored field, and no costly counting occurs. Length has no internal loops. Length IsFixedSize, IsReadOnly, IsSynchronized
Counting elements.  There are many ways to count array elements. The Count() extension method can be used to count elements, like the Length property. Count Elements
ArraySegment.  When we use arrays, we often want to read or write into the elements with indexes. ArraySegment helps here. It is an abstraction for part of an array. ArraySegment
Buffer.  This deals with bytes in large arrays. It is fast. The Buffer type acts upon bytes, not array elements. It is not helpful with object data. Buffer
Performance.  For the fastest programs, use arrays where possible. But if an array is resized often, a List is faster. Copying an array is a slow operation. Optimization
IL instructions.  C# programs are compiled into IL instructions. Consider a string array. To create the array reference, "newarr string" is emitted. To assign each element "stelem" is used. IL: newarr, stelem
Research.  An array is a collection of elements, all of a specific type. And these elements are stored together in memory. Each element is accessed by an integer index.

An array is a fixed collection of same-type data that are stored contiguously and that are accessible by an index.

Algorithms in C++ Third Edition: google.com

Arrays are the simplest and most common type of structured data.

Code Complete: google.com
With string arrays,  we store many strings together. Often a List of strings is a better choice. With int or byte arrays, we store numbers.
A review.  An array is a fixed region of memory that contains elements. Arrays store things like string references. We find them at the core of important types.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值