Sobes.tech
Junior

Ποια αντικείμενα μπορούν να χρησιμοποιηθούν σε έναν βρόχο foreach;

sobes.tech AI

Απάντηση από AI

Στον βρόχο foreach μπορούν να χρησιμοποιηθούν αντικείμενα που υλοποιούν τη διεπαφή System.Collections.IEnumerable ή System.Collections.Generic.IEnumerable<T>.

Κύριοι τύποι αντικειμένων:

  • Πίνακες (μονοδιάστατοι και πολυδιάστατοι)
  • Συλλογές που υλοποιούν IEnumerable ή IEnumerable<T>:
    • List<T>
    • Dictionary<TKey, TValue>
    • HashSet<T>
    • Queue<T> και Stack<T>
    • Άλλες κλάσεις από τους χώρους ονομάτων System.Collections και System.Collections.Generic
  • Strings (System.String - επαναλαμβάνονται χαρακτήρες)
  • Αντικείμενα που επιστρέφονται από ερωτήματα LINQ
  • Ιδιωτικοί τύποι δεδομένων που υλοποιούν μία από τις προαναφερθείσες διεπαφές.

Παράδειγμα:

// Πίνακας
string[] colors = {"κόκκινο", "πράσινο", "μπλε"};
foreach (string color in colors)
{
    // ...
}

// List<T>
List<int> numbers = new List<int> {1, 2, 3, 4, 5};
foreach (int number in numbers)
{
    // ...
}

// string
string text = "γεια";
foreach (char c in text)
{
    // ...
}

// Dictionary<TKey, TValue> επαναλαμβάνει πάνω σε KeyValuePair<TKey, TValue>
Dictionary<string, int> ages = new Dictionary<string, int>
{
    {"Alice", 30},
    {"Bob", 25}
};
foreach (KeyValuePair<string, int> entry in ages)
{
    // entry.Key, entry.Value
}

// Ιδιωτική κλάση που υλοποιεί IEnumerable<T>
public class MyCollection : IEnumerable<int>
{
    private int[] _data = {10, 20, 30};

    public IEnumerator<int> GetEnumerator()
    {
        foreach (var item in _data)
        {
            yield return item; // Χρήση του iterator
        }
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

// Χρήση της ιδιωτικής κλάσης
MyCollection myCollection = new MyCollection();
foreach (int item in myCollection)
{
    // ...
}