一維數組,多元數組,交叉數組(交錯數組)
數組:包含有相同資料類型的一組數。
格式:資料類型[] 數組的名字
一維數組:
方法一:int[] ages = new int[2]{1,2};//聲明并初始化一個一維數組,中括号裡的數字為數組中元素的個數。= ages[0]
方法二:int[] ages;//聲明一個一維數組
ages = new int[6];// 初始化一維數組
方法三:int[] ages = {1,3,4};//直接指派,建立一個含有3個元素的一維數組。
多元數組(大于等于2維的數組):
方法一:int[,] ages = new int[2,3]{undefined{1,2,3},{4,5,6}};//聲明并初始化一個二維數組(一個逗号)
方法二:int[,] ages ;
ages = new int[2,3];
方法三:int[,] age = {undefined{1,2,3},{4,5,6}};
Int[,,]三維數組(二個逗号),int[,,,]四維數組(三個逗号),。。。。。
交叉數組:數組中的數組,其元素是個數組。
Int[][] ages = new int[2][]{new int[2]{1,2},new int[3]{3,4,5}};
二維數組
int[,] myInt = new int[3, 3];
myInt[0, 0] = 1; myInt[0, 1] = 2; myInt[0, 2] = 3;
myInt[1, 0] = 4; myInt[1, 1] = 5; myInt[1, 2] = 6;
myInt[2, 0] = 7; myInt[2, 1] = 8; myInt[2, 2] = 9;
//等同于 int[,] myInt = { { 1, 2, 3 }, { 4, 5, 6 },{ 7, 8, //9 } };
for (int i = 0; i <= myInt.GetUpperBound(0); i++)
{
for (int j = 0; j <= myInt.GetUpperBound(1); j++)
{
Console.Write(myInt[i,j]+",");
}
Console.WriteLine();
}
交錯數組:int[][] myInt = new int[3][];
myInt[0] = new int[3] { 1, 2, 3 };
myInt[1] = new int[5] { 4, 5, 6, 7 ,8}; myInt[2] = new int[2] { 5, 6 };
for (int i = 0; i <= myInt.GetUpperBound(0); i++)
for (int j = 0; j < myInt[i].Length; j++)
Console.Write(myInt[i][j]+",");
} Console.WriteLine();
數組裡的方法:
Array.Clear 将Array中的系列元素設定為零。
Array.Clear(Array array,int index, int length)。
int[] a = { 3, 5, 7, 8, 9 };
Array.Clear(a, 1, 2);
foreach (int i in a)
{
Console.Write(i+",");
}
int[] b = new int[15];
Array.Copy(a, 1, b, 1, 3);
foreach (int i in b)
Console.Write(i+",");
}//輸出結果:0,5,7,8,0,0,0,0,0,0,0,0,0,0,0,
Array.Indexof判斷一個數是否存在,從左向右查找。
Array.LastIndexOf()從右向左查找
int w = Array.IndexOf(a, 2);
Console.WriteLine(w);//結果是-1.存在傳回下标,不存在傳回-1,從左向右查找
Array.Reverse()反轉數組
Array.GetLength獲得元素的個數
按照指定條件在數組中檢索元素。
public partial class Frm_Main : Form
public Frm_Main()
{
InitializeComponent();
private string[] G_str_array;//定義字元串數組字段
private void Frm_Main_Load(object sender, EventArgs e)
{
G_str_array = new string[] {//為字元串數組字段指派
"明日科技","C#程式設計詞典","C#範例大全","C#範例寶典"};
for (int i = 0; i < G_str_array.Length; i++)//循環輸出字元串
lab_Message.Text += G_str_array[i] + "\n";
}
private void txt_find_TextChanged(object sender, EventArgs e)
if (txt_find.Text != string.Empty)//判斷查找字元串是否為空
{//使用FindAll方法查找相應字元串
string[] P_str_temp = Array.FindAll (G_str_array, (s) => s.Contains(txt_find.Text));
if (P_str_temp.Length > 0)//判斷是否查找到相應字元串
txt_display.Clear();//清空控件中的字元串
foreach (string s in P_str_temp)//向控件中添加字元串
{
txt_display.Text += s + Environment.NewLine;
}
else
txt_display.Text = "沒有找到記錄";//提示沒有找到記錄
else
txt_display.Clear();//清空控件中的字元串
}
2、數組的排序:
Array類使用的QuickSort算法對數組元素進行排序。Sort()方法需要數組元素實作IComparable接口。因為簡單類型(如System.String和Int32)實作IComparable接口,是以可以對包含這些類型的元素排序。如果自定義數組排序方式,就要實作IComparable接口。這個接口定義了一個方法CompareTo(),如果比較對象相等,該方法就傳回0,如果該執行個體應排在參數對象的前面,該方法就傳回小于0的值,如果該執行個體影片在參數對象的 ,該方法就傳回大于0的值。
例:修改Person類實作IComparable<Person>接口。對LastName的值進行比較。LastName是string類型,而String類已經實作了IComparable接口,是以可以使用String類中的CompareTo方法實作代碼。如果LastName相同就比較FirstName;
public class Person : IComparable<Person>
public string FirstName { get; set; }
public string LastName { get; set; }
public override string ToString()
return String.Format("{0} {1}",
FirstName, LastName);
public int CompareTo(Person other)
if (other == null) throw new ArgumentNullException("other");
int result = this.LastName.CompareTo(other.LastName);
if (result == 0)
result = this.FirstName.CompareTo(other.FirstName);
return result;
class Program
{
static void Main()
Person[] persons = GetPersons();
SortPersons(persons);
static Person[] GetPersons()
return new Person[] {
new Person { FirstName="Damon", LastName="Hill" },
new Person { FirstName="Niki", LastName="Lauda" },
new Person { FirstName="Ayrton", LastName="Senna" },
new Person { FirstName="Graham", LastName="Hill" }
};
static void SortPersons(Person[] persons)
Array.Sort(persons);
foreach (Person p in persons)
Console.WriteLine(p);
第二種:如果Person對象的排序方式與上述不同,或者不能修改在Person類,就可以實作IComparer接口。這個接口定了方法Compare。要比較的類必須事項這個接口,IComparer接口獨立要比較的類。例:
namespace Wrox.ProCSharp.Arrays
public enum PersonCompareType
FirstName,
LastName
}
public class PersonComparer : IComparer<Person>
private PersonCompareType compareType;
public PersonComparer(PersonCompareType compareType)
this.compareType = compareType;
public int Compare(Person x, Person y)
if (x == null) throw new ArgumentNullException("x");
if (y == null) throw new ArgumentNullException("y");
switch (compareType)
case PersonCompareType.FirstName:
return x.FirstName.CompareTo(y.FirstName);
case PersonCompareType.LastName:
return x.LastName.CompareTo(y.LastName);
default:
throw new ArgumentException(
"unexpected compare type");
}
public class Person
}
}
class Program
{
SortUsingPersonComparer(persons);
static void SortUsingPersonComparer(Person[] persons)
Array.Sort(persons,
new PersonComparer(PersonCompareType.FirstName));
舉例排序:A1,A2,A10 用Array.Sort(arr);排出來就是 A1,A10,A2 而我要的是 A1,A2,A10 public class CustomComparer : System.Collections.IComparer
public int Compare(object x, object y)
string s1 = (string)x;
string s2 = (string)y;
if (s1.Length > s2.Length) return 1;
if (s1.Length < s2.Length) return -1;
for (int i = 0; i < s1.Length; i++)
if (s1[i] > s2[i]) return 1;
if (s1[i] < s2[i]) return -1;
return 0;
class Program
static void Main(string[] args)
string[] str = new string[] { "A1 ", "A2 ", "A10 " };
Array.Sort(str, new CustomComparer());//建立比較器
for (int i = 0; i < str.Length; i++)
Console.WriteLine(str[i]);
3、結構比較:
數組和元祖都實作接口IStructuralEquatable和IStructuralComparable。這兩個接口是Net4.0新增的。不僅可以比較引用,還可以比較内容。這些接口都是顯式實作的,是以使用時需要把數組和元祖強制轉換為這個接口。IStructuralEquatable接口用于比較兩個元祖或數組是否有相同的内容,IStructuralComparable接口用于給元祖或數組排序。例:
public class Person : IEquatable<Person>
public int Id { get; private set; }
return String.Format("{0}, {1} {2}", Id, FirstName, LastName);
public bool Equals(Person other)
return this.FirstName == other.FirstName && this.LastName == other.LastName;
var janet = new Person { FirstName = "Janet", LastName = "Jackson" };
Person[] persons1 = { new Person { FirstName = "Michael", LastName = "Jackson" }, janet };
Person[] persons2 = { new Person { FirstName = "Michael", LastName = "Jackson" }, janet };
if (persons1 != persons2)
Console.WriteLine("not the same reference");
if (!persons1.Equals(persons2))
Console.WriteLine("equals returns false - not the same reference");
if ((persons1 as IStructuralEquatable).Equals(persons2, EqualityComparer<Person>.Default))
Console.WriteLine("the same content");
輸出結果: not the same reference
equals returns false - not the
the same content
例:比較兩個int數組是否相等?
int[] arr1 = { 1, 2, 3 };int[] arr2 = { 1, 2, 3 };
if (arr1.Equals(arr2))
{ Console.WriteLine("相同");}
else
{ Console.WriteLine("不相同"); }
if ((arr1 as IStructuralEquatable).Equals(arr2, EqualityComparer<int>.Default))
例:比較兩個元組相等
Tuple<>類提供了兩個Equals()方法:一個重寫了Object基類中的Equals()方法,并把Object作為參數,第一個方法傳送另一個元組,這個方法使用EqualityComparer<object>.Default擷取一個ObjectEqualityComparer<object>,以進行比較。這樣,就會調用Object.Equals()方法比較元組的每一項。如果每一項都傳回true,Equals()方法的最終結果就是true,這裡因為Int和String值都相同,是以傳回true;
class TupleComparer : IEqualityComparer
public new bool Equals(object x, object y)
bool result = x.Equals(y);
public int GetHashCode(object obj)
輸出結果:
not the same reference to the tuple
equals returns true
yes, using TubpleComparer
return obj.GetHashCode();
var t1 = Tuple.Create<int, string>(1, "Stephanie");
var t2 = Tuple.Create<int, string>(1, "Stephanie");
if (t1 != t2)
Console.WriteLine("not the same reference to the tuple");
if (t1.Equals(t2))
Console.WriteLine("equals returns true");
TupleComparer tc = new TupleComparer();
if ((t1 as IStructuralEquatable).Equals(t2, tc))
Console.WriteLine("yes, using TubpleComparer");
}