C#基础——数组

时间:2025-02-11 19:44:24
  1. 一维数组,多维数组,交叉数组(交错数组)

数组:包含有相同数据类型的一组数。

格式:数据类型[] 数组的名字

          1. 一维数组:

方法一:int[] ages = new int[2]{1,2};//声明并初始化一个一维数组,中括号里的数字为数组中元素的个数。=  ages[0]

方法二:int[] ages;//声明一个一维数组

        ages = new int[6];// 初始化一维数组

方法三:int[] ages = {1,3,4};//直接赋值,创建一个含有3个元素的一维数组。

          1. 多维数组(大于等于2维的数组):

方法一:int[,] ages = new int[2,3]{{1,2,3},{4,5,6}};//声明并初始化一个二维数组(一个逗号)

方法二:int[,] ages ;

        ages = new int[2,3];

方法三:int[,] age = {{1,2,3},{4,5,6}};

Int[,,]三维数组(二个逗号),int[,,,]四维数组(三个逗号),。。。。。

          1. 交叉数组:数组中的数组,其元素是个数组。

Int[][] ages = new int[2][]{new int[2]{1,2},new int[3]{3,4,5}};

          1. 二维数组

  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 <= (0); i++)

            {

                for (int j = 0; j <= (1); j++)

                {

                    (myInt[i,j]+",");

                }

                ();

            }

          1. 交错数组: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 <= (0); i++)

            {

                for (int j = 0; j < myInt[i].Length; j++)

                {

                    (myInt[i][j]+",");

                }  ();

            }

数组里的方法:

  将Array中的系列元素设置为零。

  (Array array,int index, int length)

int[] a = { 3, 5, 7, 8, 9 };

(a, 1, 2);

foreach (int i in a)

{

(i+",");

}

int[] a = { 3, 5, 7, 8, 9 };

            int[] b = new int[15];

            (a, 1, b, 1, 3);

            foreach (int i in b)

            {

                (i+",");

            }//输出结果:0,5,7,8,0,0,0,0,0,0,0,0,0,0,0,

判断一个数是否存在,从左向右查找。

()从右向左查找

int[] a = { 3, 5, 7, 8, 9 };

            int w = (a, 2);

            (w);//结果是-1.存在返回下标,不存在返回-1,从左向右查找

()反转数组

获得元素的个数  

按照指定条件在数组中检索元素。   

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 != )//判断查找字符串是否为空

            {//使用FindAll方法查找相应字符串

                string[] P_str_temp =                     (G_str_array, (s) => (txt_find.Text));

                if (P_str_temp.Length > 0)//判断是否查找到相应字符串

                {

                    txt_display.Clear();//清空控件中的字符串

                    foreach (string s in P_str_temp)//向控件中添加字符串

                    {

                        txt_display.Text += s + ;

                    }

                }

                else

                {

                    txt_display.Clear();//清空控件中的字符串

                    txt_display.Text = "没有找到记录";//提示没有找到记录

                }

            }

            else

            {

                txt_display.Clear();//清空控件中的字符串

            }

        }

    }   

2、数组的排序:

Array类使用的QuickSort算法对数组元素进行排序。Sort()方法需要数组元素实现IComparable接口。因为简单类型(如Int32)实现IComparable接口,所以可以对包含这些类型的元素排序。如果自定义数组排序方式,就要实现IComparable接口。这个接口定义了一个方法CompareTo(),如果比较对象相等,该方法就返回0,如果该实例应排在参数对象的前面,该方法就返回小于0的值,如果该实例影片在参数对象的 ,该方法就返回大于0的值。

  例:修改Person类实现IComparable<Person>接口。对LastName的值进行比较。LastNamestring类型,而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 ("{0} {1}",

                  FirstName, LastName);

        }

        public int CompareTo(Person other)

        {

            if (other == null) throw new ArgumentNullException("other");

            int result = ();

            if (result == 0)

            {

                result = ();

            }

            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)

        {

            (persons);

            foreach (Person p in persons)

            {

                (p);

            }

        }

}

第二种:如果Person对象的排序方式与上述不同,或者不能修改在Person类,就可以实现IComparer接口。这个接口定了方法Compare。要比较的类必须事项这个接口,IComparer接口独立要比较的类。例:

namespace

{

    public enum PersonCompareType

    {

        FirstName,

        LastName

    }

    public class PersonComparer : IComparer<Person>

    {

        private PersonCompareType compareType;

        public PersonComparer(PersonCompareType 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 :

                    return ();

                case :

                    return ();

                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 ("{0} {1}",

                  FirstName, LastName);

        }    

 }

class Program

 {

        static void Main()

        {       

            Person[] persons = GetPersons();

            SortUsingPersonComparer(persons);

        }

        static void SortUsingPersonComparer(Person[] persons)

        {

            (persons,

                new PersonComparer());

            foreach (Person p in persons)

            {

                (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 用(arr);排出来就是 A1,A10,A2 而我要的是 A1,A2,A10  public class CustomComparer :

    {

        public int Compare(object x, object y)

        {

            string s1 = (string)x;

            string s2 = (string)y;

            if ( > ) return 1;

            if ( < ) return -1;

            for (int i = 0; i < ; 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 " };

            (str, new CustomComparer());//新建比较器

            for (int i = 0; i < ; i++)

                (str[i]);

        }

}

3、结构比较:

数组和元祖都实现接口IStructuralEquatableIStructuralComparable。这两个接口是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 ("{0}, {1} {2}", Id, FirstName, LastName);

        }

        public bool Equals(Person other)

        {

            if (other == null) throw new ArgumentNullException("other");

            return this.FirstName == && this.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)

                ("not the same reference");

            if (!(persons2))

                ("equals returns false - not the same reference");

            if ((persons1 as IStructuralEquatable).Equals(persons2, EqualityComparer<Person>.Default))

            {

                ("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 ((arr2))

       { ("相同");}

       else

       { ("不相同"); }

       if ((arr1 as IStructuralEquatable).Equals(arr2, EqualityComparer<int>.Default))

       { ("相同");}

例:比较两个元组相等

Tuple<>类提供了两个Equals()方法:一个重写了Object基类中的Equals()方法,并把Object作为参数,第一个方法传送另一个元组,这个方法使用EqualityComparer<object>.Default获取一个ObjectEqualityComparer<object>,以进行比较。这样,就会调用()方法比较元组的每一项。如果每一项都返回trueEquals()方法的最终结果就是true,这里因为IntString值都相同,所以返回true

    class TupleComparer : IEqualityComparer

    {

        public new bool Equals(object x, object y)

        {

            bool result = (y);

            return result;

        }

        public int GetHashCode(object obj)

        {

 

输出结果:

not the same reference to the tuple

equals returns true

yes, using TubpleComparer

            return ();

 

        }

    }

    class Program

    {

        static void Main()

        {

            var t1 = <int, string>(1, "Stephanie");

            var t2 = <int, string>(1, "Stephanie");

            if (t1 != t2)

                ("not the same reference to the tuple");

            if ((t2))

                ("equals returns true");

            TupleComparer tc = new TupleComparer();

            if ((t1 as IStructuralEquatable).Equals(t2, tc))

            {

                ("yes, using TubpleComparer");

            }        

        }

    }