Sobes.tech
Junior

Kokie objektai gali būti naudojami foreach cikle?

sobes.tech AI

Atsakymas iš AI

foreach cikle gali būti naudojami objektai, įgyvendinantys sąsają System.Collections.IEnumerable arba System.Collections.Generic.IEnumerable<T>.

Pagrindiniai objektų tipai:

  • masyvai (vieno ir daugelio matmenų)
  • kolekcijos, įgyvendinančios IEnumerable arba IEnumerable<T>:
    • List<T>
    • Dictionary<TKey, TValue>
    • HashSet<T>
    • Queue<T> ir Stack<T>
    • kiti klasės iš System.Collections ir System.Collections.Generic vardų erdvių
  • eilutės (System.String - iteruojasi per simbolius)
  • objektai, grąžinami LINQ užklausų
  • savos duomenų rūšys, įgyvendinančios vieną iš nurodytų sąsajų.

Pavyzdys:

// Masyvas
string[] colors = {"red", "green", "blue"};
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 = "hello";
foreach (char c in text)
{
    // ...
}

// Dictionary<TKey, TValue> iteruojasi per 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
}

// Savo klasė, įgyvendinanti 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; // Iteratoriaus naudojimas
        }
    }

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

// Savo klasės naudojimas
MyCollection myCollection = new MyCollection();
foreach (int item in myCollection)
{
    // ...
}