情況一:Add
List<int> list = new List<int>(); list.Add(2); list.Add(3); list.Add(5); list.Add(7);情況二:Loop & Count & clear
List<int> list = new List<int>(); list.Add(2); list.Add(3); list.Add(7); foreach (int prime in list) { Console.WriteLine(prime); } //效能會比 foreach 好 for (int i = 0; i < list.Count; i++){ Console.WriteLine(list[i]); }List.Clear;
情況三:Sort重要!
list.Sort(); 太簡單,不解釋了這比較重要,使用 LINQ 和 sort 的屬性來做排序, 以下是以字長短來排列 List<string> list = new List<string>(); list.Add("mississippi"); // 最長值 list.Add("indus"); list.Add("danube"); list.Add("nile"); // 最短值 var lengths = from element in list orderby element.Length select element;foreach (string value in lengths) { Console.WriteLine(value); }情況四:Array to List
有點少用。。。就直接用List就好了。。。int[] arr = new int[3]; arr[0] = 2; arr[1] = 3; arr[2] = 5; List<int> list = new List<int>(arr);情況五:Find 功能
List<int> list = new List<int>(new int[] { 19, 23, 29 });// 找大於20int result = list.Find(item => item > 20);Console.WriteLine(result);情況六:Join List to string
List<string> cities = new List<string>(); cities.Add("New York"); cities.Add("Mumbai"); cities.Add("Berlin"); cities.Add("Istanbul"); // Join strings into one CSV line string line = string.Join(",", cities.ToArray()); Console.WriteLine(line);情況七:Insert 功能
List<string> dogs = new List<string>(); // Example List dogs.Add("A dog"); // 內容: A dogs.Add("B dog"); // 內容: A, Bdogs.Insert(1, "C dog"); // 內容: A, C, B情況八: Remove
List<string> animals = new List<string>(); animals.Add("狗"); animals.Add("貓"); animals.Add("魚"); animals.Add("蜘蛛"); animals.Add("螞蟻"); animals.Remove("螞蟻"); // 移除螞蟻,它好像不是動物...animals.RemoveAt(3); // 移除蜘蛛,它好像也不是動物... animals.RemoveRange(0, 2); // 移除0-2...錯殺動物...哈情況九:取得 Dictionary 的 key 值
var dict = new Dictionary<int, bool>(); dict.Add(3, true); dict.Add(5, false); // Get a List of all the Keys List<int> keys = new List<int>(dict.Keys); foreach (int key in keys) { Console.WriteLine(key); }
