轉帖|其它|編輯:郝浩|2011-08-01 13:52:29.000|閱讀 1792 次
概述: 在C#代碼中使用一系列字符串(strings)并需要為其創建一個列表時,List
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
在C#代碼中使用一系列字符串(strings)并需要為其創建一個列表時,List<string>泛型類是一個用于存儲一系列字 符串(strings)的極其優秀的解決辦法。下面一起有一些List<string>泛型類的示例,一起來看看吧。
List示例
下面是一個使用C#創建一個新的一系列字符串的列表的示例,利用foreach語句循環使用其每一個字符串。請注意在代碼片段的頂部添加所需的命名空間:“using System.Collections.Generic;”,List是該命名空間里的一個泛型類型。
List<string>示例代碼:
1 using System; 2 using System.Collections.Generic; 3 4 class Program 5 { 6 static void Main() 7 { 8 List<string> cities = new List<string>(); // List of city names 9 cities.Add("San Diego"); // String element 1 10 cities.Add("Humboldt"); // 2 11 cities.Add("Los Angeles"); // 3 12 cities.Add("Auburn"); // 4 13 14 // Write each city string. 15 foreach (string city in cities) 16 { 17 Console.WriteLine(city); 18 } 19 Console.ReadKey(); 20 } 21 }
輸出:
San Diego Humboldt Los Angeles Auburn
注意代碼中的尖括號(angle brackets)。在聲明語句中尖括號<和>將string類型圍在中間,這意味著List僅能夠存儲String類型的元素。string類型可以是小寫字體的string,也可以使大寫字體的String。
使用Collection實現初始化示例
C#語法允許以一種更加清晰的辦法來實現List的初始化。使用collection進行初始化,必須使用大括號{}包圍作初始化用的值。下面示例中的注釋說明了在執行該程序時編譯器所使用的代碼。
List初始化示例代碼:
1 using System; 2 using System.Collections.Generic; 3 4 class Program 5 { 6 static void Main() 7 { 8 List<string> moths = new List<string> 9 { 10 "African armyworm", 11 "Mottled pug", 12 "Purple thug", 13 "Short-cloaked moth" 14 }; 15 // The List moth contains four strings. 16 // IL: 17 // 18 // List<string> <>g__initLocal0 = new List<string>(); 19 // <>g__initLocal0.Add("African armyworm"); 20 // // ... four more Add calls 21 // List<string> moths = <>g__initLocal0; 22 } 23 }
解釋說明。可以看到字符串列表的初始化編譯為調用一系列的Add方法。因此,二者執行起來是相似的。然而,不要超出你的需要來過多的初始化List,因為調用Add方法會增加你的資源消耗。
Var示例:
下面是一個關于var關鍵字如何與List<string>一起使用的示例。var是一個隱式關鍵字,它與使用全類型名稱編譯的結果是相同的(var是C# 3.0中新增加的一個關鍵字,在編譯器能明確判斷變量的類型時,它允許對本地類型進行推斷)。
使用var關鍵字的List示例:
1 using System; 2 using System.Collections.Generic; 3 4 class Program 5 { 6 static void Main() 7 { 8 var fish = new List<string>(); // Use var keyword for string List 9 fish.Add("catfish"); // Add string 1 10 fish.Add("rainbowfish"); // 2 11 fish.Add("labyrinth fish"); // 3 12 fish.Sort(); // Sort string list alphabetically 13 14 foreach (string fishSpecies in fish) 15 { 16 Console.WriteLine(fishSpecies); 17 } 18 Console.ReadKey(); 19 } 20 }
輸出:
catfish labyrinth fish rainbowfish
注意。List<string>的Sort方法默認按照字母順序對其字符串進行排序。它使用替換的方式實現排序,意味著你不必為排序的結果分配新的存儲空間。
總結
上面是字符串類型的List的一些示例。因為C#語言中設計了泛型類型,這些示例中沒有花費較大的裝箱與拆箱過程,因此,這里的List與 ArrayList相比,在任何情況下其效率都要高一些。在這篇文章里,我們學習了聲明并使用collection對字符串類型的List進行初始化,還 學習了其Sort方法,最后還有一個使用List作為參數的示例程序。
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn
文章轉載自:博客園