在C#代碼中使用一系列字符串(strings)並需要為其創建一個列表時,List<string>泛型類是一個用於存儲一系列字符串(strings)的極其優秀的解決辦法。下面一起有一些List<string>泛型類的示例,一起來看看吧。
List示例
下面是一個使用C#創建一個新的一系列字符串的列表的示例,利用foreach語句循環使用其每一個字符串。請注意在代碼片段的頂部添加所需的命名空間:“using System.Collections.Generic;”,List是該命名空間里的一個泛型類型。
List<string>示例代碼:
1using System;
2using System.Collections.Generic;
3
4class Program
5{
6staticvoid 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.
15foreach (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初始化示例代碼:
1using System;
2using System.Collections.Generic;
3
4class Program
5{
6staticvoid 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示例:
1using System;
2using System.Collections.Generic;
3
4class Program
5{
6staticvoid 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
14foreach (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作為參數的示例程序。