For Each...Next Deyimi (Visual Basic)For Each...Next Statement (Visual Basic)
Bir koleksiyondaki her öğe için bir deyim grubunu yineler.Repeats a group of statements for each element in a collection.
SyntaxSyntax
For Each element [ As datatype ] In group
[ statements ]
[ Continue For ]
[ statements ]
[ Exit For ]
[ statements ]
Next [ element ]
BölümlerParts
SüreTerm | TanımDefinition |
---|---|
element |
For Each İfadesinde gereklidir.Required in the For Each statement. Next Deyimde isteğe bağlı.Optional in the Next statement. Değişken.Variable. Koleksiyonun öğeleri arasında yineleme yapmak için kullanılır.Used to iterate through the elements of the collection. |
datatype |
Açık ise Option Infer (varsayılan) veya zaten bildirilirse, isteğe bağlıdır element ; Option Infer kapalıysa ve önceden bildirilmemiş olması gerekir element .Optional if Option Infer is on (the default) or element is already declared; required if Option Infer is off and element isn't already declared. Veri türü element .The data type of element . |
group |
Gereklidir.Required. Bir koleksiyon türü veya nesne olan türü olan bir değişken.A variable with a type that's a collection type or Object. Tekrarlanması gereken koleksiyona başvurur statements .Refers to the collection over which the statements are to be repeated. |
statements |
İsteğe bağlı.Optional. For Each Next İçindeki ve içindeki her öğe için çalışan arasında bir veya daha fazla deyim group .One or more statements between For Each and Next that run on each item in group . |
Continue For |
İsteğe bağlı.Optional. Denetimi döngünün başlangıcına aktarır For Each .Transfers control to the start of the For Each loop. |
Exit For |
İsteğe bağlı.Optional. Denetimi döngünün dışına aktarır For Each .Transfers control out of the For Each loop. |
Next |
Gereklidir.Required. Döngünün tanımını sonlandırır For Each .Terminates the definition of the For Each loop. |
Basit örnekSimple Example
Bir For Each
Next
koleksiyonun veya dizinin her öğesi için bir deyim kümesini yinelemek istediğinizde bir... döngüsü kullanın.Use a For Each
...Next
loop when you want to repeat a set of statements for each element of a collection or array.
İpucu
İçin A... Sonraki Ifade , bir döngünün her yinelemesini bir denetim değişkeniyle ilişkilendirebileceğiniz ve değişkenin ilk ve son değerlerini belirleyebileceğiniz zaman iyi şekilde kullanılır.A For...Next Statement works well when you can associate each iteration of a loop with a control variable and determine that variable's initial and final values. Bununla birlikte, bir koleksiyonla ilgilendiğinizde, ilk ve son değer kavramı anlamlı değildir ve koleksiyonun kaç öğe olduğunu bilmeniz gerekmez.However, when you are dealing with a collection, the concept of initial and final values isn't meaningful, and you don't necessarily know how many elements the collection has. Bu tür bir durumda,... For Each
Next
döngüsü genellikle daha iyi bir seçimdir.In this kind of case, a For Each
...Next
loop is often a better choice.
Aşağıdaki örnekte, For Each
...Next
In the following example, the For Each
…Next
ifade, bir liste koleksiyonunun tüm öğeleri boyunca yinelenir.statement iterates through all the elements of a List collection.
' Create a list of strings by using a
' collection initializer.
Dim lst As New List(Of String) _
From {"abc", "def", "ghi"}
' Iterate through the list.
For Each item As String In lst
Debug.Write(item & " ")
Next
Debug.WriteLine("")
'Output: abc def ghi
Daha fazla örnek için bkz. koleksiyonlar ve diziler.For more examples, see Collections and Arrays.
İç içe döngülerNested Loops
Bir For Each
döngüyü diğerinin içine yerleştirerek döngüleri iç içe geçirebilirsiniz.You can nest For Each
loops by putting one loop within another.
Aşağıdaki örnek iç içe geçmiş For Each
...Next
The following example demonstrates nested For Each
…Next
yapıları.structures.
' Create lists of numbers and letters
' by using array initializers.
Dim numbers() As Integer = {1, 4, 7}
Dim letters() As String = {"a", "b", "c"}
' Iterate through the list by using nested loops.
For Each number As Integer In numbers
For Each letter As String In letters
Debug.Write(number.ToString & letter & " ")
Next
Next
Debug.WriteLine("")
'Output: 1a 1b 1c 4a 4b 4c 7a 7b 7c
Döngüleri iç içe aktardığınızda her döngünün benzersiz bir element
değişkeni olmalıdır.When you nest loops, each loop must have a unique element
variable.
Ayrıca, farklı türlerde denetim yapılarını birbirleriyle iç içe geçirebilirsiniz.You can also nest different kinds of control structures within each other. Daha fazla bilgi için bkz. Iç Içe denetim yapıları.For more information, see Nested Control Structures.
İçin çık ve devam etExit For and Continue For
Exit for deyimleri yürütmenin uygulamadan çıkmasına neden olur For
...Next
The Exit For statement causes execution to exit the For
…Next
öğesini Loop ve deyimden sonraki deyime aktarır Next
.loop and transfers control to the statement that follows the Next
statement.
Continue For
İfade, denetimi döngünün bir sonraki yinelemesine hemen aktarır.The Continue For
statement transfers control immediately to the next iteration of the loop. Daha fazla bilgi için bkz. Continue bildirisi.For more information, see Continue Statement.
Aşağıdaki örnek, ve deyimlerinin nasıl kullanılacağını göstermektedir Continue For
Exit For
.The following example shows how to use the Continue For
and Exit For
statements.
Dim numberSeq() As Integer =
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
For Each number As Integer In numberSeq
' If number is between 5 and 7, continue
' with the next iteration.
If number >= 5 And number <= 8 Then
Continue For
End If
' Display the number.
Debug.Write(number.ToString & " ")
' If number is 10, exit the loop.
If number = 10 Then
Exit For
End If
Next
Debug.WriteLine("")
' Output: 1 2 3 4 9 10
Exit For
Bir döngüye herhangi bir sayıda deyim yerleştirebilirsiniz For Each
.You can put any number of Exit For
statements in a For Each
loop. İç içe döngüler içinde kullanıldığında For Each
Exit For
yürütmenin en içteki döngüden çıkmasına ve denetimi bir sonraki daha yüksek iç içe geçme düzeyine aktarmasına neden olur.When used within nested For Each
loops, Exit For
causes execution to exit the innermost loop and transfers control to the next higher level of nesting.
Exit For
genellikle bir koşul değerlendirmesinden sonra, örneğin bir If
.. Then
. ...Else
yapısı.Exit For
is often used after an evaluation of some condition, for example, in an If
...Then
...Else
structure. Exit For
Aşağıdaki koşullar için kullanmak isteyebilirsiniz:You might want to use Exit For
for the following conditions:
Tekrarlamaya devam etmek gereksiz veya imkansız.Continuing to iterate is unnecessary or impossible. Bunun nedeni hatalı bir değer veya sonlandırma isteği olabilir.This might be caused by an erroneous value or a termination request.
Bir özel durum içinde yakalandı
Try
..Catch
. ...Finally
.Exit For
Bloğunun sonunda kullanabilirsinizFinally
.An exception is caught in aTry
...Catch
...Finally
. You might useExit For
at the end of theFinally
block.Sonsuz bir döngü vardır. Bu bir döngü, büyük veya hatta sonsuz bir sayı çalıştırabilir.There an endless loop, which is a loop that could run a large or even infinite number of times. Böyle bir koşulu tespit ediyorsanız,
Exit For
döngüyü atlamak için kullanabilirsiniz.If you detect such a condition, you can useExit For
to escape the loop. Daha fazla bilgi için bkz . do... Loop deyimleri.For more information, see Do...Loop Statement.
YineleyicilerIterators
Bir koleksiyon üzerinde özel bir yineleme gerçekleştirmek için bir Yineleyici kullanırsınız.You use an iterator to perform a custom iteration over a collection. Yineleyici bir işlev veya Get
erişimci olabilir.An iterator can be a function or a Get
accessor. Yield
Tek seferde koleksiyonun her bir öğesini döndürmek için bir ifade kullanır.It uses a Yield
statement to return each element of the collection one at a time.
Bir ifadeyi kullanarak bir yineleyici çağırın For Each...Next
.You call an iterator by using a For Each...Next
statement. Döngünün her yinelemesi For Each
yineleyiciyi çağırır.Each iteration of the For Each
loop calls the iterator. Yield
Yineleyiciden bir ifadeye ulaşıldığında, Yield
deyimdeki ifade döndürülür ve koddaki geçerli konum korunur.When a Yield
statement is reached in the iterator, the expression in the Yield
statement 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.
Aşağıdaki örnek bir yineleyici işlevi kullanır.The following example uses an iterator function. Yineleyici işlevinin, Yield
için içindeki bir ifade vardır ... Sonraki döngü.The iterator function has a Yield
statement that's inside a For…Next loop. ListEvenNumbers
Yönteminde, For Each
ifade gövdesinin her yinelemesi bir sonraki ifadeye devam eden Yineleyici işlevine bir çağrı oluşturur Yield
.In the ListEvenNumbers
method, each iteration of the For Each
statement body creates a call to the iterator function, which proceeds to the next Yield
statement.
Public Sub ListEvenNumbers()
For Each number As Integer In EvenSequence(5, 18)
Debug.Write(number & " ")
Next
Debug.WriteLine("")
' Output: 6 8 10 12 14 16 18
End Sub
Private Iterator Function EvenSequence(
ByVal firstNumber As Integer, ByVal lastNumber As Integer) _
As System.Collections.Generic.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
Daha fazla bilgi için bkz. yineleyiciler, yield ekstresive Yineleyici.For more information, see Iterators, Yield Statement, and Iterator.
Teknik UygulamaTechnical Implementation
Bir... For Each``Next
When a For Each
…Next
deyimin çalışması Visual Basic, döngü başlamadan önce koleksiyonu yalnızca bir kez değerlendirir.statement runs, Visual Basic evaluates the collection only one time, before the loop starts. Deyiminiz değişiklikleri veya değişiklik engelleriyorsa element
group
, bu değişiklikler döngünün yinelemesini etkilemez.If your statement block changes element
or group
, these changes don't affect the iteration of the loop.
Koleksiyondaki tüm öğeler üzerinde kapsamlı olarak atandığında element
, For Each
döngü duraklar ve deyimden sonraki deyime geçer Next
.When all the elements in the collection have been successively assigned to element
, the For Each
loop stops and control passes to the statement following the Next
statement.
Seçenek çıkarımı açık ise (varsayılan ayarı) Visual Basic derleyici, veri türünü çıkarsalabilir element
.If Option Infer is on (its default setting), the Visual Basic compiler can infer the data type of element
. Kapalıysa ve element
döngü dışında bildirilmediyse, bunu bildiriminde bildirmeniz gerekir For Each
.If it is off and element
hasn't been declared outside the loop, you must declare it in the For Each
statement. Açıkça veri türünü bildirmek için element
bir As
yan tümce kullanın.To declare the data type of element
explicitly, use an As
clause. Öğe veri türü For Each
... yapı dışında tanımlanmamışsa Next
, kapsamı döngünün gövdesidir.Unless the data type of element is defined outside the For Each
...Next
construct, its scope is the body of the loop. element
Döngüsünün dışında ve içinde bildiremezsiniz.Note that you cannot declare element
both outside and inside the loop.
İsteğe bağlı olarak element
Next
deyimde belirtebilirsiniz.You can optionally specify element
in the Next
statement. Bu, özellikle iç içe döngüler varsa programınızın okunabilirliğini geliştirir For Each
.This improves the readability of your program, especially if you have nested For Each
loops. Karşılık gelen ifadede görünen değişkenle aynı değişkeni belirtmeniz gerekir For Each
.You must specify the same variable as the one that appears in the corresponding For Each
statement.
Bir döngünün içindeki değerini değiştirmeyi önlemek isteyebilirsiniz element
.You might want to avoid changing the value of element
inside a loop. Bunu yapmak, kodunuzun okunmasını ve hata ayıklamasını daha zor hale getirir.Doing this can make it more difficult to read and debug your code. Değerini değiştirmek group
, döngü ilk kez girildiğinde belirlenen koleksiyonu veya öğelerini etkilemez.Changing the value of group
doesn't affect the collection or its elements, which were determined when the loop was first entered.
Döngüleri iç içe aktardığınızda, Next
iç düzeyden önce bir dış iç içe düzeyi ifadesine karşılaşılırsa Next
, derleyici bir hata bildirir.When you're nesting loops, if a Next
statement of an outer nesting level is encountered before the Next
of an inner level, the compiler signals an error. Ancak, derleyici bu çakışan hatayı yalnızca her ifadede belirtirseniz tespit edebilir element
Next
.However, the compiler can detect this overlapping error only if you specify element
in every Next
statement.
Kodunuz belirli bir sırada bir koleksiyonun geçiş yöntemine bağımlıysa, For Each
Next
koleksiyonun sunduğu Numaralandırıcı nesnesinin özelliklerini bilmiyorsanız,... Loop en iyi seçim değildir.If your code depends on traversing a collection in a particular order, a For Each
...Next
loop isn't the best choice, unless you know the characteristics of the enumerator object the collection exposes. Çapraz geçiş sırası Visual Basic, ancak MoveNext Numaralandırıcı nesnesinin yöntemine göre belirlenir.The order of traversal isn't determined by Visual Basic, but by the MoveNext method of the enumerator object. Bu nedenle, koleksiyonda hangi öğenin döndürüleceğini element
veya belirli bir öğeden sonra döndürülecek bir sonraki olduğunu tahmin edemeyebilirsiniz.Therefore, you might not be able to predict which element of the collection is the first to be returned in element
, or which is the next to be returned after a given element. For
... Next
Veya Do
.. Loop
. gibi farklı bir döngü yapısı kullanarak daha güvenilir sonuçlar elde edebilirsiniz.You might achieve more reliable results using a different loop structure, such as For
...Next
or Do
...Loop
.
Çalışma zamanının içindeki öğeleri ' a dönüştürebilmelidir group
element
.The runtime must be able to convert the elements in group
to element
. [ Option Strict
] İfadesinde, hem genişletme hem de daraltma dönüştürmelerine izin verilip verilmeyeceğini ( Option Strict
kapalı, varsayılan değeri) veya yalnızca genişletme dönüştürmelerine izin verilip verilmeyeceğini ( Option Strict
açık olduğunu) denetler.The [Option Strict
] statement controls whether both widening and narrowing conversions are allowed (Option Strict
is off, its default value), or whether only widening conversions are allowed (Option Strict
is on). Daha fazla bilgi için bkz. daraltma dönüştürmeleri.For more information, see Narrowing conversions.
Veri türü, group
bir koleksiyona veya Numaralandırılabilir bir diziye başvuran bir başvuru türü olmalıdır.The data type of group
must be a reference type that refers to a collection or an array that's enumerable. En yaygın olarak bu group
IEnumerable , System.Collections
ad alanının arabirimini veya IEnumerable<T> System.Collections.Generic
ad alanının arabirimini uygulayan bir nesneye başvurur.Most commonly this means that group
refers to an object that implements the IEnumerable interface of the System.Collections
namespace or the IEnumerable<T> interface of the System.Collections.Generic
namespace. System.Collections.IEnumerable
GetEnumeratorkoleksiyon için bir Numaralandırıcı nesnesi döndüren yöntemini tanımlar.System.Collections.IEnumerable
defines the GetEnumerator method, which returns an enumerator object for the collection. Numaralandırıcı nesnesi System.Collections.IEnumerator
System.Collections
ad alanı arabirimini uygular ve Current özelliğini ve Reset ve MoveNext yöntemlerini gösterir.The enumerator object implements the System.Collections.IEnumerator
interface of the System.Collections
namespace and exposes the Current property and the Reset and MoveNext methods. Visual Basic, koleksiyonu çapraz geçirmek için bunları kullanır.Visual Basic uses these to traverse the collection.
Daraltma dönüştürmeleriNarrowing Conversions
Ne zaman Option Strict
ayarlandığında On
, daraltma dönüştürmeleri normalde derleyici hatalarına neden olur.When Option Strict
is set to On
, narrowing conversions ordinarily cause compiler errors. Ancak, ' For Each
deki öğelerinden dönüşümler, group
çalışma zamanında element
değerlendirilir ve gerçekleştirilir ve daraltma dönüştürmelerinden kaynaklanan derleyici hataları bastırılır.In a For Each
statement, however, conversions from the elements in group
to element
are evaluated and performed at run time, and compiler errors caused by narrowing conversions are suppressed.
Aşağıdaki örnekte, ' m
n
Option Strict
a ' a dönüştürme bir Long
daraltma dönüştürmesi olduğundan, için başlangıç değeri olarak atama, tarihinde derleme yapmaz Integer
.In the following example, the assignment of m
as the initial value for n
doesn't compile when Option Strict
is on because the conversion of a Long
to an Integer
is a narrowing conversion. Ancak,, öğesine atama, ' den ' e For Each
number
aynı dönüştürmeyi gerektirse de, hiçbir derleyici hatası raporlanır Long
Integer
.In the For Each
statement, however, no compiler error is reported, even though the assignment to number
requires the same conversion from Long
to Integer
. For Each
Büyük bir sayı içeren ifadede, büyük sayıya uygulandığında bir çalışma zamanı hatası oluşur ToInteger .In the For Each
statement that contains a large number, a run-time error occurs when ToInteger is applied to the large number.
Option Strict On
Module Module1
Sub Main()
' The assignment of m to n causes a compiler error when
' Option Strict is on.
Dim m As Long = 987
'Dim n As Integer = m
' The For Each loop requires the same conversion but
' causes no errors, even when Option Strict is on.
For Each number As Integer In New Long() {45, 3, 987}
Console.Write(number & " ")
Next
Console.WriteLine()
' Output: 45 3 987
' Here a run-time error is raised because 9876543210
' is too large for type Integer.
'For Each number As Integer In New Long() {45, 3, 9876543210}
' Console.Write(number & " ")
'Next
Console.ReadKey()
End Sub
End Module
IEnumerator çağrılarıIEnumerator Calls
Bir For Each
... Next
döngüsünün yürütülmesi başladığında, group
geçerli bir koleksiyon nesnesine başvuran Visual Basic doğrular.When execution of a For Each
...Next
loop starts, Visual Basic verifies that group
refers to a valid collection object. Aksi takdirde, bir özel durum oluşturur.If not, it throws an exception. Aksi takdirde, MoveNext Current ilk öğeyi döndürmek için yöntemini ve Numaralandırıcı nesnesinin özelliğini çağırır.Otherwise, it calls the MoveNext method and the Current property of the enumerator object to return the first element. Eğer MoveNext
bir sonraki öğe olmadığını gösteriyorsa, diğer bir deyişle, koleksiyon boşsa, For Each
döngü duraklar ve denetimi deyimden sonraki ifadeye geçirir Next
.If MoveNext
indicates that there is no next element, that is, if the collection is empty, the For Each
loop stops and control passes to the statement following the Next
statement. Aksi takdirde, Visual Basic element
ilk öğesine ayarlar ve ekstre bloğunu çalıştırır.Otherwise, Visual Basic sets element
to the first element and runs the statement block.
Her Visual Basic Next
deyimle karşılaştığında, ifadeye geri döner For Each
.Each time Visual Basic encounters the Next
statement, it returns to the For Each
statement. Yeniden çağırır MoveNext
ve bir Current
sonraki öğesini döndürür ve sonra da bloğu çalıştırır veya sonuca bağlı olarak döngüyü sonlandırır.Again it calls MoveNext
and Current
to return the next element, and again it either runs the block or stops the loop depending on the result. Bu işlem MoveNext
, bir sonraki öğe veya bir deyimin karşılaştığı anlamına gelene kadar devam eder Exit For
.This process continues until MoveNext
indicates that there is no next element or an Exit For
statement is encountered.
Koleksiyonu değiştirme.Modifying the Collection. Normal olarak döndürülen Numaralandırıcı nesnesi GetEnumerator herhangi bir öğeyi ekleyerek, silerek, değiştirerek veya yeniden sıralayarak koleksiyonu değiştirmenize izin vermez.The enumerator object returned by GetEnumerator normally doesn't let you change the collection by adding, deleting, replacing, or reordering any elements. For Each
... Döngüsünü başlattıktan sonra koleksiyonu değiştirirseniz Next
, Numaralandırıcı nesnesi geçersiz hale gelir ve bir sonraki erişim denemesi InvalidOperationException özel duruma neden olur.If you change the collection after you have initiated a For Each
...Next
loop, the enumerator object becomes invalid, and the next attempt to access an element causes an InvalidOperationException exception.
Ancak, bu değişikliğin engellenmesi Visual Basic tarafından belirlenir, ancak bunun yerine IEnumerable arabirimin uygulanması.However, this blocking of modification isn't determined by Visual Basic, but rather by the implementation of the IEnumerable interface. IEnumerable
Yineleme sırasında değişikliklere izin veren bir şekilde uygulanması mümkündür.It is possible to implement IEnumerable
in a way that allows for modification during iteration. Bu tür dinamik değişikliği yapmayı düşünüyorsanız, kullanmakta olduğunuz koleksiyonda uygulamanın özelliklerini anladığınızdan emin olun IEnumerable
.If you are considering doing such dynamic modification, make sure that you understand the characteristics of the IEnumerable
implementation on the collection you are using.
Koleksiyon öğelerini değiştirme.Modifying Collection Elements. CurrentNumaralandırıcı nesnesinin özelliği salt okunurve her koleksiyon öğesinin yerel bir kopyasını döndürür.The Current property of the enumerator object is ReadOnly, and it returns a local copy of each collection element. Bu, öğeleri bir For Each
... döngüsünde değiştiremeyeceğiniz anlamına gelir Next
.This means that you cannot modify the elements themselves in a For Each
...Next
loop. Yaptığınız herhangi bir değişiklik yalnızca yerel kopyayı etkiler Current
ve temel koleksiyona geri yansıtılmaz.Any modification you make affects only the local copy from Current
and isn't reflected back into the underlying collection. Ancak, bir öğe bir başvuru türü ise, gösterdiği örnek üyelerini değiştirebilirsiniz.However, if an element is a reference type, you can modify the members of the instance to which it points. Aşağıdaki örnek BackColor
her bir öğenin üyesini değiştirir thisControl
.The following example modifies the BackColor
member of each thisControl
element. Ancak, thisControl
kendisini değiştiremezsiniz.You cannot, however, modify thisControl
itself.
Sub LightBlueBackground(thisForm As System.Windows.Forms.Form)
For Each thisControl In thisForm.Controls
thisControl.BackColor = System.Drawing.Color.LightBlue
Next thisControl
End Sub
Önceki örnek, BackColor
thisControl
kendisini değiştiremese de, her öğenin üyesini değiştirebilir thisControl
.The previous example can modify the BackColor
member of each thisControl
element, although it cannot modify thisControl
itself.
Dizileri geçme.Traversing Arrays. ArraySınıfı IEnumerable arabirimini uyguladığından, tüm diziler yöntemini kullanıma sunar GetEnumerator .Because the Array class implements the IEnumerable interface, all arrays expose the GetEnumerator method. Bu,... döngüsü ile bir dizi içinde yineleyebilir For Each
Next
.This means that you can iterate through an array with a For Each
...Next
loop. Ancak, yalnızca dizi öğelerini okuyabilirsiniz.However, you can only read the array elements. Bunları değiştiremezsiniz.You cannot change them.
ÖrnekExample
Aşağıdaki örnek, C:\ içindeki tüm klasörleri listeler. sınıfını kullanarak Dizin DirectoryInfo .The following example lists all the folders in the C:\ directory by using the DirectoryInfo class.
Dim dInfo As New System.IO.DirectoryInfo("c:\")
For Each dir As System.IO.DirectoryInfo In dInfo.GetDirectories()
Debug.WriteLine(dir.Name)
Next
ÖrnekExample
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 bir sınıfın örneklerini sıralar List<T> .The example sorts instances of a 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's 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
.
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
Debug.Write(thisCar.Color.PadRight(5) & " ")
Debug.Write(thisCar.Speed.ToString & " ")
Debug.Write(thisCar.Name)
Debug.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
Ayrıca bkz.See also
- KoleksiyonlarCollections
- For...Next DeyimiFor...Next Statement
- Döngü YapılarıLoop Structures
- While...End While DeyimiWhile...End While Statement
- Do...Loop DeyimiDo...Loop Statement
- Genişletme ve Daraltma DönüşümleriWidening and Narrowing Conversions
- Nesne Başlatıcıları: Adlandırılmış ve Anonim TürlerObject Initializers: Named and Anonymous Types
- Koleksiyon BaşlatıcılarıCollection Initializers
- DizilerArrays