Koleksiyonlar (C# ve Visual Basic)
Birçok uygulama için ilgili nesnelerin gruplarını oluşturmak ve yönetmek istersiniz.Nesneler iki şekilde gruplanabilir: nesne dizisi oluşturarak veya nesne koleksiyonu oluşturarak.
Diziler; türü kesin olarak belirtilmiş sabit sayıdaki nesneleri oluştururken veya bunlarla çalışırken ekseriyetle faydalıdır.Diziler hakkında daha fazla bilgi için bkz. Visual Basic'de Diziler or Diziler (C# Programlama Kılavuzu).
Koleksiyonlar nesne grupları ile çalışmak üzere daha esnek bir yol sağlar.Dizilerden farklı olarak çalıştığınız nesne grupları, uygulamanın ihtiyacına göre dinamik olarak büyüyebilir ve küçülebilir.Bazı koleksiyonlar için koleksiyona eklediğiniz herhangi bir nesne için bir tuş atayabilirsiniz böylece tuşu kullanarak nesneyi kolayca çağırabilirsiniz.
Koleksiyon, bir sınıftır, bu nedenle yeni bir koleksiyona öğeleri eklemeden önce bu koleksiyonu bildirmelisiniz.
Koleksiyonunuz tek bir veri türünde öğeler içeriyorsa, System.Collections.Generic ad alanı içindeki sınıflardan birini kullanabilirsiniz.Genel koleksiyon tür güvenliği sağlar, bu sayede başka bir veri türü eklenemez.Bir genel koleksiyondan öğe aldığınızda veri türünü belirlemeniz veya dönüştürmeniz gerekmez.
[!NOT]
Bu konudaki örnekler için Imports deyimlerini (Visual Basic) veya System.Collections.Generic ve System.Linq ad alanları için kullanım direktiflerini (C#) dahil edin.
Bu konuda
Basit Bir Koleksiyon Kullanma
-
System.Collections.Generic Sınıfları
System.Collections.Concurrent Sınıfları
System.Collections Sınıfları
Visual Basic Collection Sınıfı
Anahtar/Değer Çiftleri Topluluğu Uygulama
Koleksiyona Erişmek için LINQ Kullanma
Koleksiyon Sıralama
Özel Koleksiyonu Tanımlama
Yineleyiciler
Basit Bir Koleksiyon Kullanma
Bu bölümdeki örnekler, türü kesin olarak belirlenmiş nesneler listesiyle çalışmanıza olanak sağlayan genel List sınıfını kullanır.
Aşağıdaki örnek bir dize listesi oluşturur ve sonra bir Her biri için...İleri (Visual Basic) veya foreach (C#) ifadesi kullanarak dizeler arasında gezinir.
' 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
Bir koleksiyonun içeriği önceden biliniyorsa koleksiyonu başlatmak için bir koleksiyon başlatıcısı kullanabilirsiniz.Daha fazla bilgi için bkz: Koleksiyon Başlatıcıları (Visual Basic) veya Nesne ve Koleksiyon Başlatıcıları (C# Programlama Kılavuzu).
Öğe eklemek için bir koleksiyon başlatıcısının kullanılması dışında aşağıdaki örnek önceki örnekle aynıdır.
' 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 Each deyimi yerine For…Next (Visual Basic) veya for (C#) deyimini kullanarak da koleksiyonda gezinebilirsiniz.Bunu, koleksiyon öğelerine dizin konumundan erişerek gerçekleştirirsiniz.Öğelerin dizini 0'da başlar ve öğe sayısı eksi 1'de sona erer.
Aşağıdaki örnek For Each yerine For…Next kullanarak bir koleksiyonun öğeleri aracılığıyla yinelenir.
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
Aşağıdaki örnek kaldırılacak nesneyi belirterek koleksiyondan bir öğe kaldırır.
' 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
Aşağıdaki örnek bir genel listeden öğeleri kaldırır.Bir For Each ifadesi yerine, azalan sırada yenileyen For…Next (Visual Basic) veya for (C#) deyimi kullanılır.Bunun nedeni, RemoveAt yönteminin kaldırılmış bir öğeden sonra gelen öğelerin daha düşün dizin değerine sahip olmasına neden olmasıdır.
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 içindeki öğe türleri için kendi sınıfınızı tanımlayabilirsiniz.Aşağıdaki örnekte, List tarafından kullanılan Galaxy sınıfı kod içinde tanımlanmıştır.
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; }
}
Koleksiyon Türleri
Ortak koleksiyonların çoğu .NET Framework tarafından sağlanır.Her koleksiyon türü belirli bir amaç için tasarlanmıştır.
Bu bölümde, aşağıdaki koleksiyon sınıfı grupları açıklanmaktadır:
System.Collections.Generic sınıfları
System.Collections.Concurrent sınıfları
System.Collections sınıfları
Visual Basic Collection sınıfı
System.Collections.Generic Sınıfları
System.Collections.Generic ad alanındaki sınıflardan birini kullanarak genel bir koleksiyon oluşturabilirsiniz.Genel koleksiyon, koleksiyondaki her öğe aynı veri türüne sahipse kullanışlıdır.Gelen koleksiyon, yalnızca istenen veri türlerinin eklenmesini sağlayarak güçlü yazmayı sağlar.
Aşağıdaki tablo, System.Collections.Generic ad alanının sık kullanılan sınıflarından bazılarını listeler:
Sınıf |
Tanımlama |
Anahtara göre düzenlenen anahtar/değer çifti koleksiyonunu temsil eder. |
|
Dizin aracılığıyla erişilebilen bir nesne listesini temsil eder.Listelerde arama, sıralama ve değiştirme için yöntemler sağlar. |
|
İlk giren ilk çıkar (FIFO) nesne koleksiyonunu temsil eder. |
|
İlişkili IComparer uygulamasına göre sıralanan anahtar/değer çifti koleksiyonunu temsil eder. |
|
Son giren ilk çıkar (LIFO) nesne koleksiyonunu temsil eder. |
Ek bilgiler için bkz. Çok Kullanılan Koleksiyon Türleri, Koleksiyon Sınıfı Seçme ve System.Collections.Generic.
System.Collections.Concurrent Sınıfları
.NET Framework 4'te System.Collections.Concurrent ad alanında bulunan koleksiyonlar koleksiyon öğelerine birden fazla iş parçacığından erişmek için verimli ve iş parçacığı açısından güvenli işlemler sağlar.
Koleksiyona birden fazla iş parçacığının eriştiği her seferde, System.Collections.Generic ve System.Collections ad alanlarındaki karşılık gelen türler yerine, System.Collections.Concurrent ad alanındaki sınıflar kullanılmalıdır.Daha fazla bilgi için, bkz. İş Parçacığı Koleksiyonları ve System.Collections.Concurrent.
System.Collections.Concurrent ad alanına eklenen bazı sınıflar şunlardır: BlockingCollection, ConcurrentDictionary, ConcurrentQueue ve ConcurrentStack.
System.Collections Sınıfları
System.Collections ad alanındaki sınıflar öğeleri özellikle yazılmış nesneler olarak değil, Object tür nesneleri olarak saklarlar.
Mümkün olduğunda genel koleksiyonları System.Collections.Generic ad alanında veya System.Collections.Concurrent ad alanında kullanmayı System.Collections ad alanındaki eski türlerde kullanmaya tercih etmelisiniz.
Aşağıdaki tablo, System.Collections ad alanında sık kullanılan sınıfların bazılarını listeler:
Sınıf |
Tanımlama |
Boyutu gerektiği şekilde dinamik olarak artırılan nesne dizilerini temsil eder. |
|
Anahtarın karma koduna göre düzenlenen anahtar/değer çifti koleksiyonunu temsil eder. |
|
İlk giren ilk çıkar (FIFO) nesne koleksiyonunu temsil eder. |
|
Son giren ilk çıkar (LIFO) nesne koleksiyonunu temsil eder. |
System.Collections.Specialized ad alanı yalnızca dize koleksiyonları, bağlantılı liste ve melez sözlükler gibi özelleştirilmiş ve türü kesin belirlenmiş koleksiyon sınıfları sağlar.
Visual Basic Collection Sınıfı
Visual Basic Collection sınıfını kullanarak sayısal dizin veya String anahtarı kullanarak bir koleksiyon öğesine erişebilirsiniz.Koleksiyon nesnesine anahtar belirterek veya belirtmeden öğe ekleyebilirsiniz.Anahtar olmadan bir öğe eklerseniz, erişmek için sayısal dizinini kullanmanız gerekir.
Visual Basic Collection sınıfı tüm öğelerini Object türünde depolar, bu sayede istediğiniz veri türünde öğe ekleyebilirsiniz.Uygun olmayan veri türlerinin eklenmesine karşın bir güvenlik önlemi yoktur.
Visual Basic Collection sınıfını kullandığınızda, koleksiyondaki ilk öğenin dizini 1 olur.Bu, başlangıç dizininin 0 olduğu .NET Framework koleksiyon sınıflarından farklıdır.
Mümkün olduğunda genel koleksiyonları System.Collections.Generic ad alanında veya System.Collections.Concurrent ad alanında kullanmayı Collection Visual Basic sınıfını kullanmaya tercih etmelisiniz.
Daha fazla bilgi için bkz. Collection.
Anahtar/Değer Çiftleri Topluluğu Uygulama
Dictionary genel koleksiyonu her öğenin anahtarını kullanarak bir koleksiyondaki öğelere erişmenize olanak sağlar.Kitaplığa yapılan her ilave bir değer ve buna ilişkin anahtardan meydana gelir.Dictionary sınıfı bir karma tablo olarak uygulandığından bir değeri anahtarını kullanarak almak oldukça hızlıdır.
Aşağıdaki örnek bir Dictionary koleksiyonu oluşturur ve bir For Each ifadesi kullanarak sözlük aracılığıyla yinelenir.
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; }
}
Bunun yerine, Dictionary koleksiyonunu oluşturmak için bir koleksiyon başlatıcı kullanmak üzere BuildDictionary ve AddToDictionary yöntemlerini aşağıdaki yöntemle değiştirebilirsiniz.
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}}
};
}
Aşağıdaki örnek, bir öğeyi anahtara göre hızlı bir şekilde bulmak üzere ContainsKey yöntemini ve Dictionary için Item özelliğini kullanır.Item özelliği, Visual Basic'deki elements(symbol) kodu veya C#'deki elements[symbol] öğesini kullanarak elements koleksiyonundaki bir öğeye erişmenize olanak sağlar.
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);
}
}
Aşağıdaki örnek, bir öğeyi anahtara göre hızlı bir şekilde bulmak için bunun yerine TryGetValue yöntemini kullanır.
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);
}
Koleksiyona Erişmek için LINQ Kullanma
LINQ (Dil ile Tümleşik Sorgu) koleksiyonlara erişmek için kullanılabilir.LINQ sorguları filtreleme, sıralama ve gruplama özellikleri sunar.Daha fazla bilgi için bkz: Visual Basic'te LINQ'e Başlarken veya C#'de LINQ'e Başlarken.
Aşağıdaki örnek, bir genel List için LINQ sorgusu çalıştırır.LINQ sorgusu sonuçları içeren farklı bir koleksiyon döndürür.
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; }
}
Koleksiyon Sıralama
Aşağıdaki örnek bir koleksiyonu sıralamak için bir yordam gösterir.Örnek List içinde depolanan Car sınıfının örneklerini sıralar.Car sınıfı CompareTo yönteminin uygulanmasını gerektiren IComparable arabirimini uygular.
CompareTo yöntemine yönelik her çağrı, sıralama için kullanılan tek bir karşılaştırma oluşturur.CompareTo yöntemindeki kullanıcı tarafından yazılmış kod, geçerli nesnenin başka bir nesneyle her karşılaştırılışında bir değer döndürür.Döndürülen değer, geçerli nesne diğer nesneden küçükse sıfırdan küçük, geçerli nesne diğer nesneden büyükse sıfırdan büyük, iki nesne eşitse sıfırdır.Bu, büyüktür, küçüktür ve eşittir için kod ölçütlerini tanımlamanızı sağlar.
ListCars yönteminde cars.Sort() deyimi listeyi sıralar.Bu Sort öğesi List yöntemi çağrısı, CompareTo yönteminin otomatik olarak Car nesnelerinin List içinde çağrılmasına neden olur.
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;
}
}
Özel Koleksiyonu Tanımlama
IEnumerable veya IEnumerable arabirimini uygulayarak bir koleksiyon tanımlayabilirsiniz.Ek bilgiler için bkz. Koleksiyon Numaralandırma ve Nasıl yapılır: foreach ile Koleksiyon Sınıfına Erişme (C# Programlama Kılavuzu).
Özel koleksiyon tanımlayabilirsiniz, ancak bunun yerine genellikle, Koleksiyon Çeşitleri'nde açıklanan .NET Framework kapsamındaki koleksiyonların kullanılması daha iyidir.
Aşağıdaki örnek AllColors adlı bir özel koleksiyon tanımlar.Bu sınıf, IEnumerable arabirimini uygular, bu arabirim GetEnumerator yönteminin uygulanmasını gerektirir.
GetEnumerator yöntemi ColorEnumerator sınıfının bir örneğini döndürür.ColorEnumerator; Current özelliği, MoveNext yöntemi ve Reset yönteminin uygulanmasını gerektiren, IEnumerator arabirimini uygular.
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; }
}
Yineleyiciler
Bir yineleyici; bir koleksiyon üzerinde özel yineleme yapmak için kullanılır.Bir yineleyici; bir yöntem veya bir get erişimcisi olabilir.Yineleyici; bir Yield (Visual Basic) veya bir yield return (C#) deyimi kullanarak, koleksiyonun her öğesini birer birer döndürür.
For Each…Next (Visual Basic) veya foreach (C#) deyimini kullanarak yineleyici çağırabilirsiniz.For Each döngüsünün her yinelemesi yineleyiciyi çağırır.Yineleyici içinde bir Yield veya yield return deyimine ulaşıldığında bir özel durum döndürülür ve kodun geçerli konumu korunur.Yürütme, yineleyicinin bir sonraki çağrılmasında bu konumdan başlar.
Daha fazla bilgi için bkz. Yineleyiciler (C# ve Visual Basic).
Aşağıdaki örnek yineleyici yöntemini kullanır.Yineleyici yöntem, bir For…Next (Visual Basic) veya for (C#) döngüsü içinde bulunan bir Yield veya yield return ifadesi içerir.ListEvenNumbers yönteminde For Each deyim gövdesinin her yinelenmesi yineleme yöntemine bir çağrı oluşturur ve bu yöntem sonraki Yield veya yield return deyimine devam eder.
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;
}
}
}
Ayrıca bkz.
Görevler
Nasıl yapılır: foreach ile Koleksiyon Sınıfına Erişme (C# Programlama Kılavuzu)
Başvuru
Nesne ve Koleksiyon Başlatıcıları (C# Programlama Kılavuzu)
Kavramlar
Koleksiyon Başlatıcıları (Visual Basic)
Koleksiyonlardaki Karşılaştırmalar ve Sıralamalar
Genel Koleksiyonları Ne Zaman Kullanılacağı
Diğer Kaynaklar
Koleksiyonlar En İyi Uygulamaları