一维数组,多维数组,交叉数组(交错数组)
数组:包含有相同数据类型的一组数。
格式:数据类型[] 数组的名字
一维数组:
方法一: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[] a = { 3, 5, 7, 8, 9 };
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[] a = { 3, 5, 7, 8, 9 };
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.Clear();//清空控件中的字符串
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
{
public string FirstName { get; set; }
public string LastName { get; set; }
public override string ToString()
{
return String.Format("{0} {1}",
FirstName, LastName);
}
}
class Program
{
static void Main()
{
Person[] persons = GetPersons();
SortUsingPersonComparer(persons);
}
static void SortUsingPersonComparer(Person[] persons)
{
Array.Sort(persons,
new PersonComparer(PersonCompareType.FirstName));
foreach (Person p in persons)
{
Console.WriteLine(p);
}
}
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" }
};
}
}
举例排序: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; }
public string FirstName { get; set; }
public string LastName { get; set; }
public override string ToString()
{
return String.Format("{0}, {1} {2}", Id, FirstName, LastName);
}
public bool Equals(Person other)
{
if (other == null) throw new ArgumentNullException("other");
return this.FirstName == other.FirstName && this.LastName == other.LastName;
}
}
class Program
{
static void Main()
{
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))
{ Console.WriteLine("相同");}
例:比较两个元组相等
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);
return result;
}
public int GetHashCode(object obj)
{
输出结果:
not the same reference to the tuple
equals returns true
yes, using TubpleComparer
return obj.GetHashCode();
}
}
class Program
{
static void Main()
{
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");
}
}
}