一. Array-数组
在C#中定义一个数组的方法一般为:
Data Type [] Array=new DataType [Size];
其中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 类型,所以在存储或检索值类型时通常发生装箱和取消装箱。
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]);