1. 程式人生 > >c#list基礎用法彙總

c#list基礎用法彙總

因為是轉載文章, 在此標明出處,如有冒犯請聯絡本人。

因為好的文章,以前只想收藏,但連線有時候會失效,所以現在碰到好的直接轉到自己這裡。

原文出處:http://www.33lc.com/article/7364.html



 C#中的List怎麼樣?List<T>類是ArrayList類的泛型等效類,該類使用大小可按需動態增加的陣列實現IList<T>泛型介面。接下來,綠茶小編就介紹一些List的基礎簡單用法。

 

  泛型的好處:它為使用c#語言編寫面向物件程式增加了極大的效力和靈活性。不會強行對值型別進行裝箱和拆箱,或對引用型別進行向下強制型別轉換,所以效能得到提高。
 

  效能注意事項:在決定使用IList<T>還是使用ArrayList類(兩者具有類似的功能)時,記住IList<T>類在大多數情況下執行得更好並且是型別安全的。如果對IList<T>類的型別T 使用引用型別,則兩個類的行為是完全相同的。但是,如果對型別T 使用值型別,則需要考慮實現和裝箱問題。
 

C# List的基礎常用方法:
 

  一、宣告:

  1、List<T> mList = new List<T>();

  T為列表中元素型別,現在以string型別作為例子:

  List<string> mList = new List<string>();
 

  2、List<T> testList =new List<T> (IEnumerable<T> collection);

  以一個集合作為引數建立List:

  string[] temArr = { "Ha", "Hunter", "Tom", "Lily", "Jay", "Jim", "Kuku", "Locu"};

  List<string> testList = new List<string>(temArr);
 

  二、新增元素:

  1、List. Add(T item)新增一個元素

  例:

  mList.Add("John");
 

  2、List. AddRange(IEnumerable<T> collection)新增一組元素

  例:

  string[] temArr = {"Ha","Hunter","Tom","Lily","Jay","Jim","Kuku","Locu"};mList.AddRange(temArr);
 

  3、Insert(intindex, T item);在index位置新增一個元素

  例:

  mList.Insert(1,"Hei");
 

  三、遍歷List中元素:

  foreach(TelementinmList)T的型別與mList宣告時一樣

  {

  Console.WriteLine(element);

  }

  例:

  foreach(stringsinmList)

  {

  Console.WriteLine(s);

  }
 

  四、刪除元素:

  1、List. Remove(T item)刪除一個值

  例:

  mList.Remove("Hunter");
 

  2、List. RemoveAt(intindex);刪除下標為index的元素

  例:

  mList.RemoveAt(0);
 

  3、List. RemoveRange(intindex,intcount);

  從下標index開始,刪除count個元素

  例:

  mList.RemoveRange(3, 2);
 

  五、判斷某個元素是否在該List中:

  List. Contains(T item)返回true或false,很實用

  例:

  if(mList.Contains("Hunter"))

  {

  Console.WriteLine("There is Hunter in the list");

  }

  else

  {

  mList.Add("Hunter");

  Console.WriteLine("Add Hunter successfully.");

  }
 

  六、給List裡面元素排序:

  List. Sort ()預設是元素第一個字母按升序

  例:

  mList.Sort();
 

  七、給List裡面元素順序反轉:

  List. Reverse ()可以不List. Sort ()配合使用,達到想要的效果

  例:

  mList.Sort();
 

  八、List清空:

  List. Clear ()

  例:

  mList.Clear();
 

  九、獲得List中元素數目:

  List. Count ()返回int值

  例:

  in tcount = mList.Count();

  Console.WriteLine("The num of elements in the list: "+count);