Koleksiyonlar (C#)Collections (C#)
Birçok uygulama için ilgili nesne grupları oluşturmak ve yönetmek istersiniz.For many applications, you want to create and manage groups of related objects. Nesneleri gruplandırmanın iki yolu vardır: nesne dizileri oluşturarak ve nesne koleksiyonları oluşturarak.There are two ways to group objects: by creating arrays of objects, and by creating collections of objects.
Diziler, kesin olarak belirlenmiş sabit sayıda nesne oluşturmak ve bunlarla çalışmak için en yararlı seçenektir.Arrays are most useful for creating and working with a fixed number of strongly typed objects. Diziler hakkında daha fazla bilgi için bkz. diziler.For information about arrays, see Arrays.
Koleksiyonlar, nesne gruplarıyla çalışmak için daha esnek bir yol sağlar.Collections provide a more flexible way to work with groups of objects. Dizilerden farklı olarak, çalıştığınız nesne grubu, uygulama değişikliğinin ihtiyaçlarına göre dinamik olarak büyüyebilir ve küçülebilir.Unlike arrays, the group of objects you work with can grow and shrink dynamically as the needs of the application change. Bazı koleksiyonlar için, anahtarı kullanarak nesneyi hızlı bir şekilde alabilmeniz için koleksiyona yerleştirdiğiniz herhangi bir nesneye bir anahtar atayabilirsiniz.For some collections, you can assign a key to any object that you put into the collection so that you can quickly retrieve the object by using the key.
Koleksiyon bir sınıftır, bu nedenle bu koleksiyona öğe ekleyebilmeniz için önce sınıfın bir örneğini bildirmeniz gerekir.A collection is a class, so you must declare an instance of the class before you can add elements to that collection.
Koleksiyonunuz yalnızca bir veri türünün öğelerini içeriyorsa, ad alanındaki sınıflardan birini kullanabilirsiniz System.Collections.Generic .If your collection contains elements of only one data type, you can use one of the classes in the System.Collections.Generic namespace. Genel bir koleksiyon, tür güvenliğini, başka bir veri türü eklenememesi için uygular.A generic collection enforces type safety so that no other data type can be added to it. Genel koleksiyondan bir öğe aldığınızda, veri türünü belirlememek veya dönüştürmek zorunda değilsiniz.When you retrieve an element from a generic collection, you do not have to determine its data type or convert it.
Not
Bu konudaki örnekler için using System.Collections.Generic
ve ad alanları için using yönergelerini içerir System.Linq
.For the examples in this topic, include using directives for the System.Collections.Generic
and System.Linq
namespaces.
Bu konudaIn this topic
Anahtar/değer çiftleri koleksiyonu uygulamaImplementing a Collection of Key/Value Pairs
Koleksiyona erişmek için LINQ kullanmaUsing LINQ to Access a Collection
Basit bir koleksiyon kullanmaUsing a Simple Collection
Bu bölümdeki örneklerde List<T> , türü kesin belirlenmiş bir nesne listesiyle çalışmanıza olanak sağlayan genel sınıfı kullanılır.The examples in this section use the generic List<T> class, which enables you to work with a strongly typed list of objects.
Aşağıdaki örnek, bir dizi dizenin bir listesini oluşturur ve sonra, bir foreach ifadesi kullanarak dizeler arasında yinelenir.The following example creates a list of strings and then iterates through the strings by using a foreach statement.
// 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.If the contents of a collection are known in advance, you can use a collection initializer to initialize the collection. Daha fazla bilgi için bkz. nesne ve koleksiyon başlatıcıları.For more information, see Object and Collection Initializers.
Aşağıdaki örnek, koleksiyona öğe eklemek için bir koleksiyon başlatıcısı kullanılması dışında, önceki örnekle aynıdır.The following example is the same as the previous example, except a collection initializer is used to add elements to the collection.
// 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
Bir for foreach
koleksiyon aracılığıyla yinelemek için bir for ifadesinin yerine bir for ifadesini kullanabilirsiniz.You can use a for statement instead of a foreach
statement to iterate through a collection. Bunu, koleksiyon öğelerine dizin konumuna erişerek gerçekleştirirsiniz.You accomplish this by accessing the collection elements by the index position. Öğelerin dizini 0 ' dan başlar ve öğe sayısı eksi 1 ' den sona erer.The index of the elements starts at 0 and ends at the element count minus 1.
Aşağıdaki örnek yerine kullanarak bir koleksiyonun öğeleri boyunca yinelenir for
foreach
.The following example iterates through the elements of a collection by using for
instead of foreach
.
// 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 öğeyi kaldırır.The following example removes an element from the collection by specifying the object to remove.
// 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, genel bir listeden öğeleri kaldırır.The following example removes elements from a generic list. Bir ifade yerine foreach
, azalan düzende yinelenen bir for deyimleri kullanılır.Instead of a foreach
statement, a for statement that iterates in descending order is used. Bunun nedeni, RemoveAt yöntemin kaldırılan bir öğeden sonra öğelerin daha düşük bir dizin değerine sahip olmasına neden olur.This is because the RemoveAt method causes elements after a removed element to have a lower index value.
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
İçindeki öğe türleri için List<T> kendi sınıfınızı de tanımlayabilirsiniz.For the type of elements in the List<T>, you can also define your own class. Aşağıdaki örnekte, Galaxy
tarafından kullanılan sınıfı List<T> kodda tanımlanmıştır.In the following example, the Galaxy
class that is used by the List<T> is defined in the code.
private static 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ürleriKinds of Collections
Birçok ortak koleksiyon .NET tarafından sağlanır.Many common collections are provided by .NET. Her koleksiyon türü belirli bir amaç için tasarlanmıştır.Each type of collection is designed for a specific purpose.
Ortak koleksiyon sınıflarından bazıları bu bölümde açıklanmıştır:Some of the common collection classes are described in this section:
System.Collections.Generic sınıflarSystem.Collections.Generic classes
System.Collections.Concurrent sınıflarSystem.Collections.Concurrent classes
System.Collections sınıflarSystem.Collections classes
System. Collections. Generic sınıflarıSystem.Collections.Generic Classes
Ad alanındaki sınıflardan birini kullanarak genel bir koleksiyon oluşturabilirsiniz System.Collections.Generic .You can create a generic collection by using one of the classes in the System.Collections.Generic namespace. Genel bir koleksiyon, koleksiyondaki her öğe aynı veri türüne sahip olduğunda faydalıdır.A generic collection is useful when every item in the collection has the same data type. Genel bir koleksiyon, yalnızca istenen veri türünün eklenmesine izin vererek güçlü yazma uygular.A generic collection enforces strong typing by allowing only the desired data type to be added.
Aşağıdaki tabloda, ad alanının sık kullanılan sınıflarının bazıları listelenmektedir System.Collections.Generic :The following table lists some of the frequently used classes of the System.Collections.Generic namespace:
SınıfClass | AçıklamaDescription |
---|---|
Dictionary<TKey,TValue> | Anahtara göre düzenlenen anahtar/değer çiftleri koleksiyonunu temsil eder.Represents a collection of key/value pairs that are organized based on the key. |
List<T> | Dizin tarafından erişilebilen nesnelerin listesini temsil eder.Represents a list of objects that can be accessed by index. Listeleri aramak, sıralamak ve değiştirmek için yöntemler sağlar.Provides methods to search, sort, and modify lists. |
Queue<T> | Nesnelerin ilk, ilk çıkar (FıFO) koleksiyonunu temsil eder.Represents a first in, first out (FIFO) collection of objects. |
SortedList<TKey,TValue> | İlişkili uygulamaya göre anahtara göre sıralanan anahtar/değer çiftleri koleksiyonunu temsil eder IComparer<T> .Represents a collection of key/value pairs that are sorted by key based on the associated IComparer<T> implementation. |
Stack<T> | Nesnelerin son, ilk çıkar (LıFO) koleksiyonunu temsil eder.Represents a last in, first out (LIFO) collection of objects. |
Daha fazla bilgi için bkz. yaygın olarak kullanılan koleksiyon türleri, koleksiyon sınıfı seçmeve System.Collections.Generic .For additional information, see Commonly Used Collection Types, Selecting a Collection Class, and System.Collections.Generic.
System. Collections. eşzamanlı sınıflarSystem.Collections.Concurrent Classes
.NET Framework 4 ve sonraki sürümlerinde, System.Collections.Concurrent ad alanındaki koleksiyonlar, koleksiyon öğelerine birden çok iş parçacığından erişmek için verimli iş parçacığı güvenli işlemleri sağlar.In .NET Framework 4 and later versions, the collections in the System.Collections.Concurrent namespace provide efficient thread-safe operations for accessing collection items from multiple threads.
System.Collections.Concurrent System.Collections.Generic System.Collections Birden çok iş parçacığının koleksiyona aynı anda eriştiği her seferinde ve ad alanındaki ilgili türler yerine ad alanındaki sınıflar kullanılmalıdır.The classes in the System.Collections.Concurrent namespace should be used instead of the corresponding types in the System.Collections.Generic and System.Collections namespaces whenever multiple threads are accessing the collection concurrently. Daha fazla bilgi için bkz. Iş parçacığı güvenli koleksiyonlar ve System.Collections.Concurrent .For more information, see Thread-Safe Collections and System.Collections.Concurrent.
Ad alanına dahil edilen bazı sınıflar System.Collections.Concurrent ,, ve ' dir BlockingCollection<T> ConcurrentDictionary<TKey,TValue> ConcurrentQueue<T> ConcurrentStack<T> .Some classes included in the System.Collections.Concurrent namespace are BlockingCollection<T>, ConcurrentDictionary<TKey,TValue>, ConcurrentQueue<T>, and ConcurrentStack<T>.
System. Collections sınıflarıSystem.Collections Classes
System.CollectionsAd alanındaki sınıflar öğeleri özel olarak yazılmış nesneler olarak depolamaz, ancak türünden nesneler olarak depolamaz Object
.The classes in the System.Collections namespace do not store elements as specifically typed objects, but as objects of type Object
.
Mümkün olduğunda, ad alanındaki System.Collections.Generic Eski türler yerine ad alanı veya ad alanı içinde genel koleksiyonları kullanmanız gerekir System.Collections.Concurrent System.Collections
.Whenever possible, you should use the generic collections in the System.Collections.Generic namespace or the System.Collections.Concurrent namespace instead of the legacy types in the System.Collections
namespace.
Aşağıdaki tabloda, ad alanında sık kullanılan sınıfların bazıları listelenmektedir System.Collections
:The following table lists some of the frequently used classes in the System.Collections
namespace:
SınıfClass | AçıklamaDescription |
---|---|
ArrayList | Boyutu dinamik olarak gerektiği şekilde arttığı bir nesne dizisini temsil eder.Represents an array of objects whose size is dynamically increased as required. |
Hashtable | Anahtarın karma koduna göre düzenlenmiş anahtar/değer çiftleri koleksiyonunu temsil eder.Represents a collection of key/value pairs that are organized based on the hash code of the key. |
Queue | Nesnelerin ilk, ilk çıkar (FıFO) koleksiyonunu temsil eder.Represents a first in, first out (FIFO) collection of objects. |
Stack | Nesnelerin son, ilk çıkar (LıFO) koleksiyonunu temsil eder.Represents a last in, first out (LIFO) collection of objects. |
System.Collections.SpecializedAd alanı, yalnızca dize toplamaları ve bağlantılı liste ve karma sözlük gibi özelleştirilmiş ve kesin tür belirtilmiş koleksiyon sınıfları sağlar.The System.Collections.Specialized namespace provides specialized and strongly typed collection classes, such as string-only collections and linked-list and hybrid dictionaries.
Anahtar/değer çiftleri koleksiyonu uygulamaImplementing a Collection of Key/Value Pairs
Dictionary<TKey,TValue>Genel koleksiyon, her bir öğenin anahtarını kullanarak bir koleksiyondaki öğelere erişmenizi sağlar.The Dictionary<TKey,TValue> generic collection enables you to access to elements in a collection by using the key of each element. Sözlüğe eklenen her ekleme bir değerden ve ilişkili anahtarından oluşur.Each addition to the dictionary consists of a value and its associated key. Dictionary
Sınıfı bir karma tablo olarak uygulandığından, anahtarını kullanarak bir değerin alınması hızlıdır.Retrieving a value by using its key is fast because the Dictionary
class is implemented as a hash table.
Aşağıdaki örnek bir koleksiyon oluşturur Dictionary
ve bir ifade kullanarak sözlükten yinelenir foreach
.The following example creates a Dictionary
collection and iterates through the dictionary by using a foreach
statement.
private static 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 static 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 static 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; }
}
Koleksiyonu oluşturmak için bir koleksiyon başlatıcısı kullanmak yerine, Dictionary
BuildDictionary
ve AddToDictionary
yöntemlerini aşağıdaki yöntemle değiştirebilirsiniz.To instead use a collection initializer to build the Dictionary
collection, you can replace the BuildDictionary
and AddToDictionary
methods with the following method.
private static 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, ContainsKey Item[] Dictionary
bir öğeyi anahtara göre hızlı bir şekilde bulmak için yöntemini ve özelliğini kullanır.The following example uses the ContainsKey method and the Item[] property of Dictionary
to quickly find an item by key. Item
Özelliği, elements
elements[symbol]
C# ' de kullanarak koleksiyondaki bir öğeye erişmenizi sağlar.The Item
property enables you to access an item in the elements
collection by using the elements[symbol]
in C#.
private static 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 bunun yerine, TryGetValue bir öğeyi anahtara göre hızlı bir şekilde bulmak için yöntemini kullanır.The following example instead uses the TryGetValue method quickly find an item by key.
private static 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 kullanmaUsing LINQ to Access a Collection
LINQ (dil ile tümleşik sorgu), koleksiyonlara erişmek için kullanılabilir.LINQ (Language-Integrated Query) can be used to access collections. LINQ sorguları filtreleme, sıralama ve gruplama özellikleri sağlar.LINQ queries provide filtering, ordering, and grouping capabilities. Daha fazla bilgi için bkz. C# ' de LINQ Ile çalışmayabaşlama.For more information, see Getting Started with LINQ in C#.
Aşağıdaki örnek, genel olarak bir LINQ sorgusu çalıştırır List
.The following example runs a LINQ query against a generic List
. LINQ sorgusu, sonuçları içeren farklı bir koleksiyon döndürür.The LINQ query returns a different collection that contains the results.
private static 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 static 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; }
}
Bir koleksiyonu sıralamaSorting a Collection
Aşağıdaki örnek bir koleksiyonu sıralamak için bir yordam gösterir.The following example illustrates a procedure for sorting a collection. Örnek, Car
içinde depolanan sınıfının örneklerini sıralar List<T> .The example sorts instances of the Car
class that are stored in a List<T>. Car
Sınıfı, IComparable<T> yönteminin uygulanması için arabirimini uygular CompareTo .The Car
class implements the IComparable<T> interface, which requires that the CompareTo method be implemented.
Yöntemine yapılan her çağrı, CompareTo sıralama için kullanılan tek bir karşılaştırma yapar.Each call to the CompareTo method makes a single comparison that is used for sorting. Yöntemdeki Kullanıcı tarafından yazılan kod, CompareTo
geçerli nesnenin her bir karşılaştırması için başka bir nesneyle ilgili bir değer döndürür.User-written code in the CompareTo
method returns a value for each comparison of the current object with another object. Geçerli nesne diğer nesneden daha küçükse döndürülen değer sıfırdan küçük, geçerli nesne diğer nesneden büyükse sıfırdan büyük ve eşitse sıfır.The value returned is less than zero if the current object is less than the other object, greater than zero if the current object is greater than the other object, and zero if they are equal. Bu, büyük, küçüktür ve eşittir ölçütlerine göre kod içinde tanımlamanızı sağlar.This enables you to define in code the criteria for greater than, less than, and equal.
Yönteminde, ListCars
cars.Sort()
ifade listeyi sıralar.In the ListCars
method, the cars.Sort()
statement sorts the list. Öğesinin yöntemine yapılan bu çağrı, Sort List<T> CompareTo
yönteminin içindeki nesneler için otomatik olarak çağrılmasına neden olur Car
List
.This call to the Sort method of the List<T> causes the CompareTo
method to be called automatically for the Car
objects in the List
.
private static 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 bir koleksiyon tanımlamaDefining a Custom Collection
Veya arabirimini uygulayarak bir koleksiyon tanımlayabilirsiniz IEnumerable<T> IEnumerable .You can define a collection by implementing the IEnumerable<T> or IEnumerable interface.
Özel bir koleksiyon tanımlamanızı mümkün olsa da, bu makalenin önceki kısımlarında yer alan koleksiyonlar türlerinde açıklanan .net ' e dahil edilen koleksiyonları kullanmak genellikle daha iyidir.Although you can define a custom collection, it is usually better to instead use the collections that are included in .NET, which are described in Kinds of Collections earlier in this article.
Aşağıdaki örnek adlı özel bir koleksiyon sınıfını tanımlar AllColors
.The following example defines a custom collection class named AllColors
. Bu sınıf, IEnumerable yönteminin uygulanması için arabirimini uygular GetEnumerator .This class implements the IEnumerable interface, which requires that the GetEnumerator method be implemented.
GetEnumerator
Yöntemi, sınıfının bir örneğini döndürür ColorEnumerator
.The GetEnumerator
method returns an instance of the ColorEnumerator
class. ColorEnumerator
IEnumerator Current özelliği, MoveNext yöntemi ve yönteminin uygulanması için arabirimini uygular Reset .ColorEnumerator
implements the IEnumerator interface, which requires that the Current property, MoveNext method, and Reset method be implemented.
private static 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; }
}
YineleyicilerIterators
Bir Yineleyici , bir koleksiyon üzerinde özel bir yineleme gerçekleştirmek için kullanılır.An iterator is used to perform a custom iteration over a collection. Yineleyici bir yöntem veya get
erişimci olabilir.An iterator can be a method or a get
accessor. Bir yineleyici, tek seferde koleksiyonun her bir öğesini döndürmek için bir yield return ifadesini kullanır.An iterator uses a yield return statement to return each element of the collection one at a time.
Bir foreach ifadesi kullanarak bir yineleyici çağırın.You call an iterator by using a foreach statement. Döngünün her yinelemesi foreach
yineleyiciyi çağırır.Each iteration of the foreach
loop calls the iterator. yield return
Yineleyiciden bir ifadeye ulaşıldığında, bir ifade döndürülür ve koddaki geçerli konum korunur.When a yield return
statement is reached in the iterator, an expression is returned, and the current location in code is retained. Bu konumdan, yineleyici bir sonraki sefer çağrıldığında yürütme yeniden başlatılır.Execution is restarted from that location the next time that the iterator is called.
Daha fazla bilgi için bkz. yineleyiciler (C#).For more information, see Iterators (C#).
Aşağıdaki örnek bir yineleyici yöntemi kullanır.The following example uses an iterator method. Yineleyici yöntemi yield return
için bir for döngüsü içinde olan bir ifade vardır.The iterator method has a yield return
statement that is inside a for loop. ListEvenNumbers
Yönteminde, ifade gövdesinin her yinelemesi, foreach
bir sonraki ifadeye devam eden Yineleyici yöntemine bir çağrı oluşturur yield return
.In the ListEvenNumbers
method, each iteration of the foreach
statement body creates a call to the iterator method, which proceeds to the next yield return
statement.
private static 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.See also
- Nesne ve Koleksiyon BaşlatıcılarıObject and Collection Initializers
- Programlama kavramları (C#)Programming Concepts (C#)
- Option Strict DeyimiOption Strict Statement
- LINQ to Objects (C#)LINQ to Objects (C#)
- Paralel LINQ (PLINQ)Parallel LINQ (PLINQ)
- Koleksiyonlar ve veri yapılarıCollections and Data Structures
- Koleksiyon Sınıfı SeçmeSelecting a Collection Class
- Koleksiyonlar Içinde karşılaştırmalar ve sıralamalarComparisons and Sorts Within Collections
- Genel Koleksiyonlar ne zaman kullanılır?When to Use Generic Collections