一. Array-數組
在C#中定義一個數組的方法一般為:
Data Type [] Array=new DataType [Size];
其中Data Type可以是基礎資料型別 (Elementary Data Type)和物件類型資料,Size是數組元素的個數.
例子定義一個int類型的資料來表示一個班上的人數
int [] classNum=new int[20];
數組的屬性有:
屬性
意義
public virtual bool IsFixedSize
數組的長度是否是固定的
public virtual bool IsReadOnly
數組是否是唯讀型
public virtual bool IsSynchronized
在多線程環境下是否安全
public int Length
數組元素的個數
public int Rank
數組的維數
public virtual object SyncRoot
同步訪問數組對象
數組對象的方法有靜態方法和執行個體方法;
public static int BinarySearch(Array a, object v);
數組a必須是一維而且排好序的;此方法的結果是返回a中與v匹配的第一個元素的索引號.如果沒有匹配元素則返回一個負數-1;
public static int BinarySearch(Array a, object v, IComparer comp);
與前面的方法相似,區別在於comp;用於比較符號;
public static int BinarySearch(Array a, int start,int count, object v)
從a中start開始的count個元素中查詢與v匹配的元素的一個索引號.
public static int BinarySearch(Array a, int start,int count, object v,IComparer comp)
與上一個方法相似.區別在於用比較法補償;
public static void Clear(Array a, int start, int count)
將數組a中從start開始的從count個元素置零;
public virtual object Clone()Copy這個數組;
public static void Copy(Array source,Array dest, int count)
將source中的count個元素賦值到數組dest中.;
public virtual void CopyTo(Array dest, int start)
將調用此方法的數組對象中的start個元素賦值到dest中.
public static Array CreateInstance(Type t, int size)
建立一個有Size個元素的數組,其中元素類型是t;
public static Array CreateInstance(Type t, int size1, int size2)
建立一個二維數組,數組的參數是[size1][size2];數組元素的類型是t;
public static Array CreateInstance(Type t, int size1,int size2, int size3)
建立一個三維數組,元素類型是T,同建立二維數組一樣.;
public static Array CreateInstance(Type t, int[ ] sizes)
建立一個參數sizes維的數組,元素類型是t;
public static Array CreateInstance(Type t, int[ ] sizes,int[ ] startIndexes)
建立一個多維陣列,數組維數是sizes,每一個元素的資料類型是t.數組中每一維數組的開始索引號是startIndexes;
public override bool Equals(object v)
判斷v是否與調用此方法的數組對象是否相同.
public virtual IEnumerator GetEnumerator()
返回數組的枚舉對象
public int GetLength(int dim)
返回多維陣列第dim維的元素的個數
public override int GetHashCode()
返回數組的雜湊碼;
public int GetUpperBound(int dim)
返回多維陣列第dim維的元素的最後一個索引值
public object GetValue(int index) 返回一維數組第index個元素的值
public object GetValue(int idx1, int idx2)和public object GetValue(int idx1, int idx2,int idx3)分別擷取2維和3維數組的某個特殊元素的值.;
public static int IndexOf(Array a, object v) 返回a中與v的值一樣的第一元素的索引值;
public static int IndexOf(Array a, object v,int start)
從a中第start個元素開始,返回與v的值一樣的元素位置;
public static int IndexOf(Array a, object v,int start, int count)
從a中第start個元素開始的count個元素中,返回與v的值一樣的元素位置;
public static int LastIndexOf(Array a, object v,int start, int count)
在a中得第start個元素開始的count個元素中尋找與v相等的元素的索引號
public static void Reverse(Array a) 將數組a所有元素做個逆轉;
public void SetValue(object v, int index) 設定數組對象的第index個元素的值為v;
對象二維和三維數組有相似的函數;public void SetValue(object v, int idx1, int idx2)和public void SetValue(object v, int idx1,int idx2, int idx3)
public static void Sort(Array a) 對數組a進行排序;
二. 定義和初始化一個數組
int[] myIntArray; myIntArray = new int[4]; 利用數組的函數IndexOf() and LastIndexOf()來擷取數組中某一個特定元素的位置;
int[] intArray = {1, 2, 1, 3};
Console.WriteLine("intArray:");
for (int i = 0; i < intArray.Length; i++)
{
Console.WriteLine("intArray[" + i + "] = " +
intArray[i]);}
int index = Array.IndexOf(intArray, 1);
Console.WriteLine("Array.IndexOf(intArray, 1) = " + index);
index = Array.LastIndexOf(intArray, 1);
Console.WriteLine("Array.LastIndexOf(intArray, 1) = " + index);
一. C#數組的屬性
一維數組和多維(二維以上)的數組的屬性和方法都是差不多的,主要是在數組的方法上有些參數的不一致,現在我們先看下一維數組的有關屬性;
int[] myint = new int[5];
for (int x = 1; x <= 5; x++)
myint[x - 1] = x;
Console.WriteLine("顯示數組中的資料");
for (int i = 1; i <= 5; i++)
Console.WriteLine("第{0}個元素的值是{1}", i, myint[i-1]);
Console.WriteLine("顯示數組的性質");
Console.WriteLine(myint.IsFixedSize);//是否固定大小
Console.WriteLine(myint.IsReadOnly);// 是否唯讀
Console.WriteLine(myint.IsSynchronized);//是否非同步作業
Console.WriteLine(myint.Length);//數組的長度
Console.WriteLine(myint.LongLength);//數組的長度
Console.WriteLine(myint.Rank);//數組的維數
Console.WriteLine(myint.SyncRoot);//數組的對象
運行圖如下:
數組元素的索引號是從0開始的,myint[0] 是數組的第一個元素,其最後一個元素是myint[ArraySize-1].如果索引號的值大於等於數組的長度,則會出現錯誤異常:
二. C#數組提供的方法
1. 常用的執行個體對象方法
Console.WriteLine(Array.IndexOf(myint,3));
//擷取數組中元素為3在數組中的索引號
Console.WriteLine(Array.LastIndexOf(myint, 3));
//擷取數組中元素為3在數組中的索引號,數組中最後與3匹配
Console.WriteLine(Array.AsReadOnly(myint));//
Array.Reverse(myint);//將數組的元素
for (int i = 1; i <= 5; i++)
Console.WriteLine("第{0}個元素的值是{1}", i, myint[i - 1]);
Console.WriteLine(myint.GetLength(0));//擷取指定維數的元素數
Console.WriteLine(myint.GetLongLength(0));
Console.WriteLine(myint.GetLowerBound(0));//擷取指定維數的下限;
Console.WriteLine(myint.GetType());//當前執行個體對象的類型
Console.WriteLine(myint.GetValue(2));//擷取數組中索引號為2的元素的值
Console.WriteLine(myint.GetHashCode());//擷取對象的雜湊嗎
Console.WriteLine(myint.ToString());
Console.WriteLine(myint.GetEnumerator());//擷取對象的枚舉
myint.SetValue(111,0);//設定{newValue,index_of_Array
Console.WriteLine(myint[0]);
Console.WriteLine("Clone方法");
int[] orignalArray = { 1, 2, 3 };
int[] cloneArray = (int[])orignalArray.Clone();//複製一個新的一樣的數組
cloneArray[0] = 10;
cloneArray[1] = 20;
cloneArray[2] = 30;
foreach (int i in orignalArray)
Console.WriteLine(i);
foreach (int i in cloneArray)
Console.WriteLine(i);
int[] copyArr = new int[myint.Length];
myint.CopyTo(copyArr,0);//複製一個數組到另一個數組
Console.WriteLine("{0},{1},{2},{3},{4}", copyArr[0], copyArr[1], copyArr[2], copyArr[3], copyArr[4]);
Console.WriteLine("{0},{1},{2},{3},{4}", myint[0], myint[1], myint[2], myint[3], myint[4]);
int[] array_1 = new int[5];
for (int i = array_1.GetLowerBound(0); i <= array_1.GetUpperBound(0); i++)
array_1[i] = i + 1;//擷取指定維數的下限 擷取指定維數的上限
for (int j = array_1.GetLowerBound(0); j <= array_1.GetUpperBound(0); j++)
Console.WriteLine("array_1[{0}] = {1}", j, array_1[j]);
// This program illustrates various ways to
// create and manipulate array types.
//
// Comment / uncomment method calls in Main()
// to test.
using System;
using System.Collections.Generic;
using System.Text;
namespace FunWithArrays
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Arrays *****");
SimpleArrays();
ArrayInitialization();
ArrayOfObjects();
RectMultidimensionalArray();
JaggedMultidimensionalArray();
PassAndReceiveArrays();
SystemArrayFunctionality();
Console.ReadLine();
}
#region Helper methods
static void SimpleArrays()
{
Console.WriteLine("=> Simple Array Creation.");
// Create and fill an array of 3 Integers
int[] myInts = new int[3];
myInts[0] = 100;
myInts[1] = 200;
myInts[2] = 300;
// Now print each value.
foreach (int i in myInts)
Console.WriteLine(i);
Console.WriteLine();
}
static void ArrayInitialization()
{
Console.WriteLine("=> Array Initialization.");
// Array initialization syntax using the new keyword.
string[] stringArray = new string[] { "one", "two", "three" };
Console.WriteLine("stringArray has {0} elements", stringArray.Length);
// Array initialization syntax without using the new keyword.
bool[] boolArray = { false, false, true };
Console.WriteLine("boolArray has {0} elements", boolArray.Length);
// Array initialization with new keyword and size.
int[] intArray = new int[4] { 20, 22, 23, 0 };
Console.WriteLine("intArray has {0} elements", intArray.Length);
Console.WriteLine();
}
static void ArrayOfObjects()
{
Console.WriteLine("=> Array of Objects.");
// An array of objects can be anything at all.
object[] myObjects = new object[4];
myObjects[0] = 10;
myObjects[1] = false;
myObjects[2] = new DateTime(1969, 3, 24);
myObjects[3] = "Form & Void";
foreach (object obj in myObjects)
{
// Print the type and value for each item in array.
Console.WriteLine("Type: {0}, Value: {1}", obj.GetType(), obj);
}
Console.WriteLine();
}
static void RectMultidimensionalArray()
{
Console.WriteLine("=> Rectangular multidimensional array.");
// A rectangular MD array.
int[,] myMatrix;
myMatrix = new int[6, 6];
// Populate (6 * 6) array.
for (int i = 0; i < 6; i++)
for (int j = 0; j < 6; j++)
myMatrix[i, j] = i * j;
// Print (6 * 6) array.
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 6; j++)
Console.Write(myMatrix[i, j] + "\t");
Console.WriteLine();
}
Console.WriteLine();
}
static void JaggedMultidimensionalArray()
{
//鋸齒形多維陣列
Console.WriteLine("=> Jagged multidimensional array.");
// A jagged MD array (i.e., an array of arrays).
// Here we have an array of 5 different arrays.
int[][] myJagArray = new int[5][];
// Create the jagged array.
for (int i = 0; i < myJagArray.Length; i++)
myJagArray[i] = new int[i + 7];
// Print each row (remember, each element is defaulted to zero!)
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < myJagArray[i].Length; j++)
Console.Write(myJagArray[i][j] + " ");
Console.WriteLine();
}
Console.WriteLine();
}
static void PrintArray(int[] myInts)
{
for (int i = 0; i < myInts.Length; i++)
Console.WriteLine("Item {0} is {1}", i, myInts[i]);
}
static string[] GetStringArray()
{
string[] theStrings = { "Hello", "from", "GetStringArray" };
return theStrings;
}
static void PassAndReceiveArrays()
{
Console.WriteLine("=> Arrays as params and return values.");
int[] ages = { 20, 22, 23, 0 };
PrintArray(ages);
string[] strs = GetStringArray();
foreach (string s in strs)
Console.WriteLine(s);
Console.WriteLine();
}
static void SystemArrayFunctionality()
{
Console.WriteLine("=> Working with System.Array.");
// Initialize items at startup.
string[] gothicBands = { "Tones on Tail", "Bauhaus", "Sisters of Mercy" };
// Print out names in declared order.
Console.WriteLine(" -> Here is the array:");
//數組上界GetUpperBound
for (int i = 0; i <= gothicBands.GetUpperBound(0); i++)
{
// Print a name
Console.Write(gothicBands[i] + " ");
}
Console.WriteLine("\n");
// Reverse them...
// 反轉數組
Array.Reverse(gothicBands);
Console.WriteLine(" -> The reversed array");
// ... and print them.
for (int i = 0; i <= gothicBands.GetUpperBound(0); i++)
{
// Print a name
Console.Write(gothicBands[i] + " ");
}
Console.WriteLine("\n");
// Clear out all but the final member.
Console.WriteLine(" -> Cleared out all but one...");
Array.Clear(gothicBands, 1, 2);
for (int i = 0; i <= gothicBands.GetUpperBound(0); i++)
{
// Print a name
Console.Write(gothicBands[i] + " ");
}
Console.WriteLine();
}
#endregion
}
}
二、ArrayList
Array是個靜態數組,一旦數組大小在初始化過程中確定了在後面就不能修改了,也不能對數組中的元素進行增加和刪除.這不是很靈活,為此C#提供了ArrayList用來處理動態數組.,
ArrayList在建立以後可以根據實際需要進行元素的增刪.這個是非常好用了..我們先看下ArrayList的建構函式
ArrayList al = new ArrayList();
再來看一個簡單的例子:
ArrayList al = new ArrayList();
Console.WriteLine
("Initial number of elements: " + al.Count);
Console.WriteLine("Adding 6 elements");
// Add elements to the array list
al.Add('C');
al.Add('A');
al.Add('E');
al.Add('B');
al.Add('D');
al.Add('F');
al.Remove('A');//刪除一個元素
Console.WriteLine(al.Count);
al.Add('a');//增加一個元素
Console.WriteLine(al.Count);
al[0] = 'X';//修改數組元素
al[1] = 'Y';
al[2] = 'Z';
//刪除一個元素後數量變為5,增加一個後元素的數量為6
那麼現在我們再來建立一個數位ArrayList來學習下它的方法;
ArrayList al = new ArrayList();
// Add elements to the array list
al.Add(155); al.Add(413);
al.Add(-41); al.Add(818);
al.Add(31); al.Add(191);
Console.Write("Original contents: ");
foreach(int i in al)
Console.Write(i + " ");
Console.WriteLine("\n");
// Sort 排序
al.Sort();
Console.Write("Contents after sorting: ");
foreach(int i in al)
Console.Write(i + " ");
Console.WriteLine("\n");
Console.WriteLine("Index of 413 is " +
al.BinarySearch(413));
一. ArrayList相關方法的學習
利用enumerator來訪問數組:
ArrayList list = new ArrayList(1);
for (int i = 0; i < 10; i++)
list.Add(i);
IEnumerator etr = list.GetEnumerator();//枚舉
while (etr.MoveNext())
Console.Write(etr.Current + " ");
運行結果:
對了,要想在C#中利用ArrayList必須在系統命名空間中加入一個引用,否則會出現錯誤的。using System.Collections;
下面看一些動態數組的常用方法:
ArrayList list = new ArrayList(5);
//構造一個動態數組
// list.Clear();//清楚數組中所有的元素
Console.WriteLine();
Console.WriteLine("there are {0} elements in the list", list.Count);
ArrayList shuzu = new ArrayList(5);
shuzu.Add("仙劍一");
shuzu.Add("亮劍");
shuzu.Add("bianceng.");
shuzu.Add("國家寶藏");
shuzu.Add("陸小鳳");
for (int x = 0; x <= shuzu.Count - 1; x++)
Console.WriteLine(shuzu[x]);
Console.WriteLine("now reverse it\n");
shuzu.Reverse();
Console.WriteLine("after reverser\n");
Console.WriteLine();
for (int x = 0; x <= shuzu.Count - 1; x++)
Console.WriteLine(shuzu[x]);
運行結果:
現在比較下array 和arraylist:Array 提供 ArrayList 所不具有的某些靈活性。例如:
可以設定 Array 的下限,但 ArrayList 的下限始終為零。
Array 可以具有多個維度,而 ArrayList 始終只是一維的;特定類型(不包括 Object)的 Array 的效能比 ArrayList 好,這是因為 ArrayList 的元素屬於 Object 類型,所以在儲存或檢索實值型別時通常發生裝箱和unboxing。
Array 位於 System 命名空間中;ArrayList 位於 System. Collections 命名空間中
至於ArrayList從Object類繼承下來的父類方法我在這裡就不多介紹了,
那都是些基本的方法。下面看些ArrayList使用的方法。
Console.WriteLine();
for (int x = 0; x <= shuzu.Count - 1; x++)
Console.WriteLine(shuzu[x]);
Console.WriteLine("there are {0} elements in the list", shuzu.Count);
Console.WriteLine("now add a new elements ");
shuzu.Add("new element");//增加一個元素
Console.WriteLine("there are {0} elements in the list", shuzu.Count);
shuzu.Remove("亮劍");//刪除特點元素
Console.WriteLine("there are {0} elements in the list", shuzu.Count);
shuzu.RemoveAt(2);//刪除指定位置的元素
Console.WriteLine("there are {0} elements in the list", shuzu.Count);
shuzu.Insert(1, "系統級");//在數組的制定位置插入一個元素
Console.WriteLine("there are {0} elements in the list", shuzu.Count);
int countElement = shuzu.Count;
Console.WriteLine(shuzu.GetType());//輸出數組的類型
int index = shuzu.IndexOf("系統級");//擷取某一元素的索引號
Console.WriteLine();
ArrayList anothe = new ArrayList(shuzu);//建立一個數組
for (int b = 0; b < anothe.Count; b++)
Console.WriteLine(anothe[b]);
Console.WriteLine(shuzu.Contains("國家寶藏"));//判定數組中是否存在某一元素
Console.WriteLine(shuzu.LastIndexOf("國家寶藏"));
list.Add("B");
list.Add("G");
list.Add("J");
list.Add("S");
list.Add("M");
string[] array1 = new string[list.Count];
//建立一個i和shuzu元素個數大小一樣大的字串數組
list.CopyTo(array1, 0);
//將shuzu中從第一個元素開始以後的元素複製到array
object[] array2 = list.ToArray();//利用這個方法建立數組
Console.WriteLine("Array 1:");
foreach (string s in array2)
{
Console.Write("{0}", s);
}
Console.WriteLine();
foreach (string s in array1)
{
Console.Write("{0}", s);
}
Console.WriteLine();
for (int i = 0; i < list.Count; i++)
Console.Write(list[i]);