C#中的數組和List


一.數組的聲明與初始化

類型 [] 數組名稱 =new 類型 [數組大小];  //必須使用new初始化

二維數組:int [ , ] tem=new int [5,6];

 

C#中,我們在創建二維數組的時候,一般使用arr[][]的形式,例如

int[][] aInt = new int[2][];


但聲明二維數組還有一種方法,是使用arr[,]的形式。兩者有什么區別呢?

實際上,形如arr[,]只能聲明等長的二維數組,例如

int[,] ab1 = new int [2,3];//默認值為0;
int[,] ab2 = new int[2,3]{{1,2,3},{4,5,6}};

形如arr[][]的形式則可以聲明等長二維數組,也可以聲明不等長二維數組。例如

int [][] abc = new int[2][];
abc[0] = new int[]{1,2};
abc[1] = new int[]{3,4,5,6};


如果我們要建立的二維數組是等長的,我們就可以大膽地使用arr[,]的形式來聲明了!
---------------------
二、用array代替二維數組

List<List<int>> array = new List<List<int>>();
List<int> item = new List<int>(new int[] { 3, 4, 5, 6 });
array.Add(item);
item = new List<int>(new int[] { 30, 40, 50, 60 });
array.Add(item);
int m = array[1][2];//此時的m即為50

List的一般用法
所屬命名空間: System.Collections.Generic
public class List<T>:IList<T>,Icollection<T>,IEnumerable<T>,IList,Icollection,Ienumerable
List<T>是ArrayList類的泛型等效類,該類使用大小可按需動態增加的數組實現IList<T>泛型接口

(1)聲明 List<T>mlist = new List<T>();
 eg: string[] Arr = {"a","b","c"};
     List<string> mlist = new List<string>(Arr);

(2)添加一個元素 List.Add(T item) 
   eg: mlist.Add("d");

(3)添加集合元素
   eg: string[] Arr2 ={"f","g"."h"};
       mlist.AddRange(Arr2);

(4)在index位置添加一個元素 Insert(int index,T item)
   eg: mlist.Insert(1,"p");

(5)遍歷List中元素

  foreach(T element in mlist) T的類型與mlist聲明時一樣
     {
       Console.WriteLine(element);
          }

    eg:
    foreach(string s in mlist)
          {
             Console.WriteLine(s);
           }

(6)刪除元素

    List.Remove(T item) 刪除一個值
    eg: mlist.Remove("a");

    List.RemoveAt(int index);刪除下標為index的元素
    eg: mlist.RemoveAt(0);
    
    List.RemoveRange(int index,int count); 下標index開始,刪除count個元素
    eg:mlist.RemoveRange(3,2);

(7)判斷某個元素是否在該List中

    List.Contains(T item) 返回true或false
    eg:
    if(mlist.Contains"("g"))
       Console.WriteLine("g存在列表中");
    else
       mlist.Add("g");

(8)給List里面元素排序 List.Sort() 默認是元素每一個字母按升序
   eg: mlist.Sort();

(9)給List里面元素順序反轉 List.Reverse() 可以與List.Sort()配合使用

(10)List清空 List.Clear()
   eg: mlist.Clear();

(11)獲得List中元素數目 List.Count() 返回int值
   eg: mlist.count();


List進階,強大方法

(12)List.FindAll方法:檢索與指定謂詞所定義的條件相匹配的所有元素 
    
    class program
    {
       static void Main(stirng[] args)
       {
         student stu = new student();
         stu.Name="arron";
         List<student> students= new List<student>();
         students.Add(stu);
         students.Add(new student("candy"));
         FindName myname = new FindName("arron");
         foreach(student s in students.FindAll(new Predicate<student>(myname.IsName)))
         { Console.WriteLine(s);}
       }

    public class student
    {
       public string Name{get;set;}
       public student(){}
       public override string ToString()
        {
            return string.Format("姓名:{0}",Name);
         }
     }

    public class FindName
    {
      private string _name;
      public FindName(string Name)
      {  this._name=Name;}
      public bool IsName(student s)
       { return (s.Name==_name)?true:false;}
    }


(12)List.Find方法 搜索與指定謂詞所定義的條件相匹配的元素,並返回整個List中的第一個匹配元素

  eg:

    //Predicate是對方法的委托,如果傳遞給它的對象與委托定義的條件匹配,則該方法返回true,當前List的元素
  被逐個傳遞給Predicate委托,並在List中間前移動,從第一個元素開始,到最后一個元素結束,當找到匹配項
  時處理停止

  第一種方法 委托給拉姆達表達式:
  eg:  
     string listFind = mlist.Find(name=>
       {
          if(name.length>3)
             return true;
          return false;
       });

    第二種方法 委托給一個函數
    eg:
     public bool ListFind(string name)

        {

            if (name.Length > 3)

            {

                return true;

            }

            return false;

        }

      這兩種方法的結果是一樣的

(13) List.FindLast方法  public T FindLast(Predicate<T> match);確定是否 List 中的每個元素都與指定的謂詞所定義的條件相匹配。用法與List.Find相同。


(14) List.TrueForAll方法:  確定是否 List 中的每個元素都與指定的謂詞所定義的條件相匹配。

 public bool TrueForAll(Predicate<T> match);

(15) List.Take(n):  獲得前n行 返回值為IEnumetable<T>,T的類型與List<T>的類型一樣

E.g.:

IEnumerable<string> takeList=  mList.Take(5);

          foreach (string s in takeList)

          {

              Console.WriteLine("element in takeList: " + s);

          }

       這時takeList存放的元素就是mList中的前5個

(16) List.Where方法:檢索與指定謂詞所定義的條件相匹配的所有元素。跟List.FindAll方法類似。

E.g.:

            IEnumerable<string> whereList = mList.Where(name =>

                {

                    if (name.Length > 3)

                    {

                        return true;

                    }

                    else

                    {

                        return false;

                    }

                });

         foreach (string s in subList)

         {

             Console.WriteLine("element in subList: "+s);

         }

         這時subList存儲的就是所有長度大於3的元素

(17)List.RemoveAll方法:移除與指定的謂詞所定義的條件相匹配的所有元素。

public int RemoveAll(Predicate<T> match);

E.g.:

            mList.RemoveAll(name =>

                {

                    if (name.Length > 3)

                    {

                        return true;

                    }

                    else

                    {

                        return false;

                    }

                });

            foreach (string s in mList)

            {

                Console.WriteLine("element in mList:     " + s);

            }

      這時mList存儲的就是移除長度大於3之后的元素。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM