集合 (C# 和 Visual Basic)
您可能希望能夠在許多應用程式中建立和管理相關物件的群組。群組物件的方式有二:建立物件的陣列和建立物件的集合。
綜合上述原因,陣列是最適用於建立和使用固定數目的強型別 (Strongly Typed) 物件。如需陣列的詳細資訊,請參閱Visual Basic 中的陣列 或 陣列 (C# 程式設計手冊)。
集合提供一個較具彈性的方式在使用物件群組方面則。與陣列不同的是,您使用的物件群組可依程式變更的需要來動態增減。對於某些集合,您可以將機碼加入至使用索引鍵到任何您放入集合的物件,讓您可以藉由使用這個索引鍵快速擷取物件。
集合是一種類別 (Class),因此在將元素加入至集合之前必須先宣告新集合。
若集合受限於只有一種資料型別的元素,則可使用 System.Collections.Generic 命名空間內的類別之一。「泛型」(Generic) 集合會強制「型別安全」(Type Safety),如此就不會加入其他資料型別。當您從泛型集合中擷取元素,並不需要判斷其資料型別或將之轉換。
注意事項 |
---|
如需本主題中的範例,請將 匯入 陳述式 (Visual Basic) 或 使用 指示詞 (C#) System.Collections.Generic 和 System.Linq 命名空間。 |
本主題內容
使用簡單的集合
集合的種類
System.Collections.Generic Classes
System.Collections.Concurrent 類別
System.Collections 類別
Visual Basic 集合類別
實作包含索引鍵/值組的集合。
使用 LINQ 存取一個集合
為集合排序
定義客製化的集合
Iterators
使用簡單的集合
本節中的範例使用泛型 List<T> 類別,能夠讓您使用物件強型別清單搭配使用。
下列範例示範建立字串清單並掃過字串,您可以使用 For Each…Next (Visual Basic) 或 foreach (C#) 陳述式。
' Create a list of strings.
Dim salmons As New List(Of String)
salmons.Add("chinook")
salmons.Add("coho")
salmons.Add("pink")
salmons.Add("sockeye")
' Iterate through the list.
For Each salmon As String In salmons
Console.Write(salmon & " ")
Next
'Output: chinook coho pink sockeye
// Create a list of strings.
var salmons = new List<string>();
salmons.Add("chinook");
salmons.Add("coho");
salmons.Add("pink");
salmons.Add("sockeye");
// Iterate through the list.
foreach (var salmon in salmons)
{
Console.Write(salmon + " ");
}
// Output: chinook coho pink sockeye
如果集合的內容事先知道,您可以使用 集合初始 設定式來初始化集合。如需詳細資訊,請參閱集合初始設定式 (Visual Basic)或物件和集合初始設定式 (C# 程式設計手冊)。
下列範例與前一個範例相同,但有一點除外,就是集合初始設定式是用來將項目加入至集合中。
' Create a list of strings by using a
' collection initializer.
Dim salmons As New List(Of String) From
{"chinook", "coho", "pink", "sockeye"}
For Each salmon As String In salmons
Console.Write(salmon & " ")
Next
'Output: chinook coho pink sockeye
// Create a list of strings by using a
// collection initializer.
var salmons = new List<string> { "chinook", "coho", "pink", "sockeye" };
// Iterate through the list.
foreach (var salmon in salmons)
{
Console.Write(salmon + " ");
}
// Output: chinook coho pink sockeye
您可以使用 For…Next (Visual Basic) 或 (C#) 針對 陳述式 (而不是 For Each 陳述式來逐一查看集合。您可以藉由存取集合項目的索引位置來完成這項作業。項目的索引開始在 0 結束在項目的計數減 1。
下列範例會逐一查看集合的項目,使用 For…Next 而不是 For Each。
Dim salmons As New List(Of String) From
{"chinook", "coho", "pink", "sockeye"}
For index = 0 To salmons.Count - 1
Console.Write(salmons(index) & " ")
Next
'Output: chinook coho pink sockeye
// Create a list of strings by using a
// collection initializer.
var salmons = new List<string> { "chinook", "coho", "pink", "sockeye" };
for (var index = 0; index < salmons.Count; index++)
{
Console.Write(salmons[index] + " ");
}
// Output: chinook coho pink sockeye
下列範例可以從項目的集合中移除指定的物件。
' Create a list of strings by using a
' collection initializer.
Dim salmons As New List(Of String) From
{"chinook", "coho", "pink", "sockeye"}
' Remove an element in the list by specifying
' the object.
salmons.Remove("coho")
For Each salmon As String In salmons
Console.Write(salmon & " ")
Next
'Output: chinook pink sockeye
// Create a list of strings by using a
// collection initializer.
var salmons = new List<string> { "chinook", "coho", "pink", "sockeye" };
// Remove an element from the list by specifying
// the object.
salmons.Remove("coho");
// Iterate through the list.
foreach (var salmon in salmons)
{
Console.Write(salmon + " ");
}
// Output: chinook pink sockeye
下列範例會移除泛型清單中的項目。不是 For Each 陳述式,For…Next (Visual Basic) 或 針對 (C#) 陳述式使用以遞減順序逐一重複的方式。這是因為 RemoveAt 方法導致在已移除之項目後面的項目具有較低的索引值。
Dim numbers As New List(Of Integer) From
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
' Remove odd numbers.
For index As Integer = numbers.Count - 1 To 0 Step -1
If numbers(index) Mod 2 = 1 Then
' Remove the element by specifying
' the zero-based index in the list.
numbers.RemoveAt(index)
End If
Next
' Iterate through the list.
' A lambda expression is placed in the ForEach method
' of the List(T) object.
numbers.ForEach(
Sub(number) Console.Write(number & " "))
' Output: 0 2 4 6 8
var numbers = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
// Remove odd numbers.
for (var index = numbers.Count - 1; index >= 0; index--)
{
if (numbers[index] % 2 == 1)
{
// Remove the element by specifying
// the zero-based index in the list.
numbers.RemoveAt(index);
}
}
// Iterate through the list.
// A lambda expression is placed in the ForEach method
// of the List(T) object.
numbers.ForEach(
number => Console.Write(number + " "));
// Output: 0 2 4 6 8
如需在 List<T>中項目的型別,您也可以定義自己的類別。在下列範例中,List<T> 使用的 Galaxy 類別在程式碼中定義。
Private Sub IterateThroughList()
Dim theGalaxies As New List(Of Galaxy) From
{
New Galaxy With {.Name = "Tadpole", .MegaLightYears = 400},
New Galaxy With {.Name = "Pinwheel", .MegaLightYears = 25},
New Galaxy With {.Name = "Milky Way", .MegaLightYears = 0},
New Galaxy With {.Name = "Andromeda", .MegaLightYears = 3}
}
For Each theGalaxy In theGalaxies
With theGalaxy
Console.WriteLine(.Name & " " & .MegaLightYears)
End With
Next
' Output:
' Tadpole 400
' Pinwheel 25
' Milky Way 0
' Andromeda 3
End Sub
Public Class Galaxy
Public Property Name As String
Public Property MegaLightYears As Integer
End Class
private void IterateThroughList()
{
var theGalaxies = new List<Galaxy>
{
new Galaxy() { Name="Tadpole", MegaLightYears=400},
new Galaxy() { Name="Pinwheel", MegaLightYears=25},
new Galaxy() { Name="Milky Way", MegaLightYears=0},
new Galaxy() { Name="Andromeda", MegaLightYears=3}
};
foreach (Galaxy theGalaxy in theGalaxies)
{
Console.WriteLine(theGalaxy.Name + " " + theGalaxy.MegaLightYears);
}
// Output:
// Tadpole 400
// Pinwheel 25
// Milky Way 0
// Andromeda 3
}
public class Galaxy
{
public string Name { get; set; }
public int MegaLightYears { get; set; }
}
集合的種類
.NET Framework 會提供很多常見的集合各個類型的集合都是針對特定用途來設計。
下列集合類別的群組將在本節做介紹:
System.Collections.Generic類別
System.Collections.Concurrent類別
System.Collections類別
[Visual Basic] Collection類別
System.Collections.Generic Classes
特別是,藉由使用 System.Collections.Generic 命名空間的其中一個類別,您可以建立「泛型」(Generic) 集合。當集合中每個項目的資料型別相同時,泛型集合就相當有用。透過只加入所要的資料型別,泛型集合強制採用「強型別」(Strong Typing)。
下表列出一些 System.Collections.Generic 命名空間的常用類別:
類別 |
描述 |
[ T:System.Collections.Generic.Dictionary`2 ] |
表示根據索引鍵,所整理的索引鍵/值組集合。 |
[ T:System.Collections.Generic.List`1 ] |
表示可以依照索引存取的強型別物件清單。提供搜尋、排序和管理清單的方法。 |
[ T:System.Collections.Generic.Queue`1 ] |
表示物件的先進先出 (First-In First-Out,FIFO) 集合。 |
[ T:System.Collections.Generic.SortedList`2 ] |
表示根據關聯的 IComparer<T> 實作,依索引鍵所排序的索引鍵/值組集合。 |
[ T:System.Collections.Generic.Stack`1 ] |
代表物件的後進先出集合。 |
如需其他資訊,請參閱 常用的集合型別、選取集合類別 和 System.Collections.Generic。
System.Collections.Concurrent 類別
在.NET Framework 4中,System.Collections.Concurrent 命名空間中的集合提供有效率的安全執行緒作業,從多個執行緒存取集合項目。
在System.Collections.Concurrent 命名空間中的類別應該被使用來代替 System.Collections.Generic 和 System.Collections 命名空間中的對應型別,每當有多個執行緒同時存取集合時。如需詳細資訊,請參閱安全執行緒集合與System.Collections.Concurrent。
包括在System.Collections.Concurrent命名空間中的類別有 BlockingCollection<T>ConcurrentDictionary<TKey, TValue>ConcurrentQueue<T>和ConcurrentStack<T>。
System.Collections 類別
System.Collections 命名空間中的類別不會將項目儲存為特殊型別的物件,而是儲存為型別 Object 的物件。
可能的話,請盡量使用 System.Collections.Generic 或 System.Collections.Concurrent 命名空間中的泛型集合,而非 System.Collections 命名空間中的舊版型別。
下表列出一些 System.Collections 命名空間的常用類別:
類別 |
描述 |
[ T:System.Collections.ArrayList ] |
表示會視需要動態增加陣列物件大小。 |
[ T:System.Collections.Hashtable ] |
表示根據索引鍵的雜湊程式碼,所整理的索引鍵/值組集合。 |
[ T:System.Collections.Queue ] |
表示物件的先進先出 (First-In First-Out,FIFO) 集合。 |
[ T:System.Collections.Stack ] |
代表物件的後進先出集合。 |
System.Collections.Specialized 命名空間會提供特製化型別和強型別集合類別,例如只有字串的集合,以及連結串列和 Hybrid 字典。
Visual Basic 集合類別
使用數值索引或 String 金鑰,您就可以使用 Visual Basic Collection 類別來存取集合項目。不論是否指定索引鍵,您都可以在集合物件中加入項目。如果加入不具索引鍵的項目,則必須使用它的數值索引加以存取。
Visual Basic Collection類別會將其所有項目儲存為型別 Object ,因此可以加入屬於任何資料型別的項目。無法確定加入的資料型別皆適當無誤。
當您使用 Visual Basic Collection 類別時,集合中的第一個項目的索引為 1。這與 .NET Framework 集合類別不同,起始索引為 0。
可能的話,請盡量使用 System.Collections.Generic 或 System.Collections.Concurrent 命名空間中的泛型集合,而非 Collection 命名空間中的舊版型別。
如需詳細資訊,請參閱Collection。
實作包含索引鍵/值組的集合。
使用每個項目,索引鍵 Dictionary<TKey, TValue> 泛型集合可讓您存取集合中的項目。加入字典中的每一個項目都是由值及其關聯索引鍵所組成。使用其索引鍵擷取值的速度非常快 (接近 O(1)),這是因為 Dictionary 類別是實作為雜湊表。
您可以使用 For Each 陳述式,下列範例會建立 Dictionary 集合並逐一查看字典。
Private Sub IterateThroughDictionary()
Dim elements As Dictionary(Of String, Element) = BuildDictionary()
For Each kvp As KeyValuePair(Of String, Element) In elements
Dim theElement As Element = kvp.Value
Console.WriteLine("key: " & kvp.Key)
With theElement
Console.WriteLine("values: " & .Symbol & " " &
.Name & " " & .AtomicNumber)
End With
Next
End Sub
Private Function BuildDictionary() As Dictionary(Of String, Element)
Dim elements As New Dictionary(Of String, Element)
AddToDictionary(elements, "K", "Potassium", 19)
AddToDictionary(elements, "Ca", "Calcium", 20)
AddToDictionary(elements, "Sc", "Scandium", 21)
AddToDictionary(elements, "Ti", "Titanium", 22)
Return elements
End Function
Private Sub AddToDictionary(ByVal elements As Dictionary(Of String, Element),
ByVal symbol As String, ByVal name As String, ByVal atomicNumber As Integer)
Dim theElement As New Element
theElement.Symbol = symbol
theElement.Name = name
theElement.AtomicNumber = atomicNumber
elements.Add(Key:=theElement.Symbol, value:=theElement)
End Sub
Public Class Element
Public Property Symbol As String
Public Property Name As String
Public Property AtomicNumber As Integer
End Class
private void IterateThruDictionary()
{
Dictionary<string, Element> elements = BuildDictionary();
foreach (KeyValuePair<string, Element> kvp in elements)
{
Element theElement = kvp.Value;
Console.WriteLine("key: " + kvp.Key);
Console.WriteLine("values: " + theElement.Symbol + " " +
theElement.Name + " " + theElement.AtomicNumber);
}
}
private Dictionary<string, Element> BuildDictionary()
{
var elements = new Dictionary<string, Element>();
AddToDictionary(elements, "K", "Potassium", 19);
AddToDictionary(elements, "Ca", "Calcium", 20);
AddToDictionary(elements, "Sc", "Scandium", 21);
AddToDictionary(elements, "Ti", "Titanium", 22);
return elements;
}
private void AddToDictionary(Dictionary<string, Element> elements,
string symbol, string name, int atomicNumber)
{
Element theElement = new Element();
theElement.Symbol = symbol;
theElement.Name = name;
theElement.AtomicNumber = atomicNumber;
elements.Add(key: theElement.Symbol, value: theElement);
}
public class Element
{
public string Symbol { get; set; }
public string Name { get; set; }
public int AtomicNumber { get; set; }
}
若不想使用集合初始設定式建立 Dictionary 集合,您可以使用下列方法取代 BuildDictionary 和 AddToDictionary 方法。
Private Function BuildDictionary2() As Dictionary(Of String, Element)
Return New Dictionary(Of String, Element) From
{
{"K", New Element With
{.Symbol = "K", .Name = "Potassium", .AtomicNumber = 19}},
{"Ca", New Element With
{.Symbol = "Ca", .Name = "Calcium", .AtomicNumber = 20}},
{"Sc", New Element With
{.Symbol = "Sc", .Name = "Scandium", .AtomicNumber = 21}},
{"Ti", New Element With
{.Symbol = "Ti", .Name = "Titanium", .AtomicNumber = 22}}
}
End Function
private Dictionary<string, Element> BuildDictionary2()
{
return new Dictionary<string, Element>
{
{"K",
new Element() { Symbol="K", Name="Potassium", AtomicNumber=19}},
{"Ca",
new Element() { Symbol="Ca", Name="Calcium", AtomicNumber=20}},
{"Sc",
new Element() { Symbol="Sc", Name="Scandium", AtomicNumber=21}},
{"Ti",
new Element() { Symbol="Ti", Name="Titanium", AtomicNumber=22}}
};
}
下列範例會使用 ContainsKey 方法和 DictionaryItem 屬性索引鍵快速尋找項目。使用 Visual Basic, 藉由使用elements(symbol) 的程式碼 Item 在 C# 中, 可讓您存取在 elements 集合中的項目或 elements[symbol] 。
Private Sub FindInDictionary(ByVal symbol As String)
Dim elements As Dictionary(Of String, Element) = BuildDictionary()
If elements.ContainsKey(symbol) = False Then
Console.WriteLine(symbol & " not found")
Else
Dim theElement = elements(symbol)
Console.WriteLine("found: " & theElement.Name)
End If
End Sub
private void FindInDictionary(string symbol)
{
Dictionary<string, Element> elements = BuildDictionary();
if (elements.ContainsKey(symbol) == false)
{
Console.WriteLine(symbol + " not found");
}
else
{
Element theElement = elements[symbol];
Console.WriteLine("found: " + theElement.Name);
}
}
下列範例會使用 TryGetValue 方法依索引鍵來快速尋找項目。
Private Sub FindInDictionary2(ByVal symbol As String)
Dim elements As Dictionary(Of String, Element) = BuildDictionary()
Dim theElement As Element = Nothing
If elements.TryGetValue(symbol, theElement) = False Then
Console.WriteLine(symbol & " not found")
Else
Console.WriteLine("found: " & theElement.Name)
End If
End Sub
private void FindInDictionary2(string symbol)
{
Dictionary<string, Element> elements = BuildDictionary();
Element theElement = null;
if (elements.TryGetValue(symbol, out theElement) == false)
Console.WriteLine(symbol + " not found");
else
Console.WriteLine("found: " + theElement.Name);
}
使用 LINQ 存取一個集合
LINQ (Language-Integrated Query (LINQ)) 可用來存取集合。LINQ 查詢,提供篩選、排序和分組功能。如需詳細資訊,請參閱使用 Visual Basic 撰寫 LINQ 入門或開始使用 C# 中的 LINQ。
下列範例會執行 LINQ 查詢 List泛型。LINQ 查詢會傳回包含結果的不同的集合。
Private Sub ShowLINQ()
Dim elements As List(Of Element) = BuildList()
' LINQ Query.
Dim subset = From theElement In elements
Where theElement.AtomicNumber < 22
Order By theElement.Name
For Each theElement In subset
Console.WriteLine(theElement.Name & " " & theElement.AtomicNumber)
Next
' Output:
' Calcium 20
' Potassium 19
' Scandium 21
End Sub
Private Function BuildList() As List(Of Element)
Return New List(Of Element) From
{
{New Element With
{.Symbol = "K", .Name = "Potassium", .AtomicNumber = 19}},
{New Element With
{.Symbol = "Ca", .Name = "Calcium", .AtomicNumber = 20}},
{New Element With
{.Symbol = "Sc", .Name = "Scandium", .AtomicNumber = 21}},
{New Element With
{.Symbol = "Ti", .Name = "Titanium", .AtomicNumber = 22}}
}
End Function
Public Class Element
Public Property Symbol As String
Public Property Name As String
Public Property AtomicNumber As Integer
End Class
private void ShowLINQ()
{
List<Element> elements = BuildList();
// LINQ Query.
var subset = from theElement in elements
where theElement.AtomicNumber < 22
orderby theElement.Name
select theElement;
foreach (Element theElement in subset)
{
Console.WriteLine(theElement.Name + " " + theElement.AtomicNumber);
}
// Output:
// Calcium 20
// Potassium 19
// Scandium 21
}
private List<Element> BuildList()
{
return new List<Element>
{
{ new Element() { Symbol="K", Name="Potassium", AtomicNumber=19}},
{ new Element() { Symbol="Ca", Name="Calcium", AtomicNumber=20}},
{ new Element() { Symbol="Sc", Name="Scandium", AtomicNumber=21}},
{ new Element() { Symbol="Ti", Name="Titanium", AtomicNumber=22}}
};
}
public class Element
{
public string Symbol { get; set; }
public string Name { get; set; }
public int AtomicNumber { get; set; }
}
為集合排序
下列範例說明如何排序集合的方法。此範例排序儲存在 List<T>中的 Car 類別的執行個體。Car 類別實作 IComparable<T> 介面,要求實作CompareTo 方法。
每次呼叫CompareTo 方法都做一次用來排序的單一比較。在 CompareTo 方法的使用者撰寫的程式碼會傳回目前物件的每個和另一個物件的比較的值。如果目前物件比另一個物件小則傳回的值小於零,如果目前物件比另一個物件大則傳回的值大於零,如果它們相等則回傳零。這可讓您定義字碼大於,小於,等於的準。
在 ListCars 方法, cars.Sort() 陳述式排序清單。為 List<T> 的 Sort 方法的呼叫會導致 CompareTo 方法對 List的 Car 物件自動呼叫。
Public Sub ListCars()
' Create some new cars.
Dim cars As New List(Of Car) From
{
New Car With {.Name = "car1", .Color = "blue", .Speed = 20},
New Car With {.Name = "car2", .Color = "red", .Speed = 50},
New Car With {.Name = "car3", .Color = "green", .Speed = 10},
New Car With {.Name = "car4", .Color = "blue", .Speed = 50},
New Car With {.Name = "car5", .Color = "blue", .Speed = 30},
New Car With {.Name = "car6", .Color = "red", .Speed = 60},
New Car With {.Name = "car7", .Color = "green", .Speed = 50}
}
' Sort the cars by color alphabetically, and then by speed
' in descending order.
cars.Sort()
' View all of the cars.
For Each thisCar As Car In cars
Console.Write(thisCar.Color.PadRight(5) & " ")
Console.Write(thisCar.Speed.ToString & " ")
Console.Write(thisCar.Name)
Console.WriteLine()
Next
' Output:
' blue 50 car4
' blue 30 car5
' blue 20 car1
' green 50 car7
' green 10 car3
' red 60 car6
' red 50 car2
End Sub
Public Class Car
Implements IComparable(Of Car)
Public Property Name As String
Public Property Speed As Integer
Public Property Color As String
Public Function CompareTo(ByVal other As Car) As Integer _
Implements System.IComparable(Of Car).CompareTo
' A call to this method makes a single comparison that is
' used for sorting.
' Determine the relative order of the objects being compared.
' Sort by color alphabetically, and then by speed in
' descending order.
' Compare the colors.
Dim compare As Integer
compare = String.Compare(Me.Color, other.Color, True)
' If the colors are the same, compare the speeds.
If compare = 0 Then
compare = Me.Speed.CompareTo(other.Speed)
' Use descending order for speed.
compare = -compare
End If
Return compare
End Function
End Class
private void ListCars()
{
var cars = new List<Car>
{
{ new Car() { Name = "car1", Color = "blue", Speed = 20}},
{ new Car() { Name = "car2", Color = "red", Speed = 50}},
{ new Car() { Name = "car3", Color = "green", Speed = 10}},
{ new Car() { Name = "car4", Color = "blue", Speed = 50}},
{ new Car() { Name = "car5", Color = "blue", Speed = 30}},
{ new Car() { Name = "car6", Color = "red", Speed = 60}},
{ new Car() { Name = "car7", Color = "green", Speed = 50}}
};
// Sort the cars by color alphabetically, and then by speed
// in descending order.
cars.Sort();
// View all of the cars.
foreach (Car thisCar in cars)
{
Console.Write(thisCar.Color.PadRight(5) + " ");
Console.Write(thisCar.Speed.ToString() + " ");
Console.Write(thisCar.Name);
Console.WriteLine();
}
// Output:
// blue 50 car4
// blue 30 car5
// blue 20 car1
// green 50 car7
// green 10 car3
// red 60 car6
// red 50 car2
}
public class Car : IComparable<Car>
{
public string Name { get; set; }
public int Speed { get; set; }
public string Color { get; set; }
public int CompareTo(Car other)
{
// A call to this method makes a single comparison that is
// used for sorting.
// Determine the relative order of the objects being compared.
// Sort by color alphabetically, and then by speed in
// descending order.
// Compare the colors.
int compare;
compare = String.Compare(this.Color, other.Color, true);
// If the colors are the same, compare the speeds.
if (compare == 0)
{
compare = this.Speed.CompareTo(other.Speed);
// Use descending order for speed.
compare = -compare;
}
return compare;
}
}
定義客製化的集合
您可以透過實作 IEnumerable<T> 或 IEnumerable 介面來定義集合。如需其他資訊,請參閱 列舉集合 和 HOW TO:使用 foreach 存取集合類別 (C# 程式設計手冊)。
雖然您可以定義自訂集合,通常不使用包含在 .NET Framework 中,使用先前說明本主題中的 Kinds of Collections 集合通常較佳。
下列範例會定義名稱為 AllColors 的客製化集合類別。這個類別 實作IEnumerable介面,要求實作 GetEnumerator 方法。
方法會傳回這個 GetEnumeratorColorEnumerator 類別的執行個體。ColorEnumerator 實作IEnumerator 介面,要求 Current 屬性、方法和 MoveNextReset 方法實作。
Public Sub ListColors()
Dim colors As New AllColors()
For Each theColor As Color In colors
Console.Write(theColor.Name & " ")
Next
Console.WriteLine()
' Output: red blue green
End Sub
' Collection class.
Public Class AllColors
Implements System.Collections.IEnumerable
Private _colors() As Color =
{
New Color With {.Name = "red"},
New Color With {.Name = "blue"},
New Color With {.Name = "green"}
}
Public Function GetEnumerator() As System.Collections.IEnumerator _
Implements System.Collections.IEnumerable.GetEnumerator
Return New ColorEnumerator(_colors)
' Instead of creating a custom enumerator, you could
' use the GetEnumerator of the array.
'Return _colors.GetEnumerator
End Function
' Custom enumerator.
Private Class ColorEnumerator
Implements System.Collections.IEnumerator
Private _colors() As Color
Private _position As Integer = -1
Public Sub New(ByVal colors() As Color)
_colors = colors
End Sub
Public ReadOnly Property Current() As Object _
Implements System.Collections.IEnumerator.Current
Get
Return _colors(_position)
End Get
End Property
Public Function MoveNext() As Boolean _
Implements System.Collections.IEnumerator.MoveNext
_position += 1
Return (_position < _colors.Length)
End Function
Public Sub Reset() Implements System.Collections.IEnumerator.Reset
_position = -1
End Sub
End Class
End Class
' Element class.
Public Class Color
Public Property Name As String
End Class
private void ListColors()
{
var colors = new AllColors();
foreach (Color theColor in colors)
{
Console.Write(theColor.Name + " ");
}
Console.WriteLine();
// Output: red blue green
}
// Collection class.
public class AllColors : System.Collections.IEnumerable
{
Color[] _colors =
{
new Color() { Name = "red" },
new Color() { Name = "blue" },
new Color() { Name = "green" }
};
public System.Collections.IEnumerator GetEnumerator()
{
return new ColorEnumerator(_colors);
// Instead of creating a custom enumerator, you could
// use the GetEnumerator of the array.
//return _colors.GetEnumerator();
}
// Custom enumerator.
private class ColorEnumerator : System.Collections.IEnumerator
{
private Color[] _colors;
private int _position = -1;
public ColorEnumerator(Color[] colors)
{
_colors = colors;
}
object System.Collections.IEnumerator.Current
{
get
{
return _colors[_position];
}
}
bool System.Collections.IEnumerator.MoveNext()
{
_position++;
return (_position < _colors.Length);
}
void System.Collections.IEnumerator.Reset()
{
_position = -1;
}
}
}
// Element class.
public class Color
{
public string Name { get; set; }
}
Iterators
Iterator 是用來執行在集合的自訂反覆項目。Iterator 可以是方法或 get 存取子。Iterator 使用 yield (Visual Basic) 或 (C#) yield return 陳述式來傳回集合中的每個項目一次。
您可以使用 For Each…Next (Visual Basic) 或 foreach (C#) 陳述式來呼叫 Iterator。For Each 迴圈反覆運算時呼叫 Iterator。當 Yield 或 yield return 陳述式在 Iterator 時為止,運算式都會傳回,並將目前位置在程式碼中保留。下一次呼叫此 Iterator 時,便會從這個位置重新開始執行。
如需詳細資訊,請參閱Iterator (C# 和 Visual Basic)。
下列範例使用了 iterator方法。Iterator 方法具有在 For…Next 的 Yield 或 yield return 陳述式 (Visual Basic) 或 (C#)的 for 迴圈內。在 ListEvenNumbers 方法,For Each 陳述式主體的每個反覆項目建立呼叫 Iterator 方法,繼續執行下個 Yield 或 yield return 陳述式。
Public Sub ListEvenNumbers()
For Each number As Integer In EvenSequence(5, 18)
Console.Write(number & " ")
Next
Console.WriteLine()
' Output: 6 8 10 12 14 16 18
End Sub
Private Iterator Function EvenSequence(
ByVal firstNumber As Integer, ByVal lastNumber As Integer) _
As IEnumerable(Of Integer)
' Yield even numbers in the range.
For number = firstNumber To lastNumber
If number Mod 2 = 0 Then
Yield number
End If
Next
End Function
private void ListEvenNumbers()
{
foreach (int number in EvenSequence(5, 18))
{
Console.Write(number.ToString() + " ");
}
Console.WriteLine();
// Output: 6 8 10 12 14 16 18
}
private static IEnumerable<int> EvenSequence(
int firstNumber, int lastNumber)
{
// Yield even numbers in the range.
for (var number = firstNumber; number <= lastNumber; number++)
{
if (number % 2 == 0)
{
yield return number;
}
}
}
請參閱
工作
HOW TO:使用 foreach 存取集合類別 (C# 程式設計手冊)