Sobes.tech
Junior

Kādi objekti var tikt izmantoti foreach ciklā?

sobes.tech AI

Atbilde no AI

foreach ciklā var tikt izmantoti objekti, kas īsteno saskarni System.Collections.IEnumerable vai System.Collections.Generic.IEnumerable<T>.

Galvenie objektu tipi:

  • masīvi (viena un daudzdimensiju)
  • kolekcijas, kas īsteno IEnumerable vai IEnumerable<T>:
    • List<T>
    • Dictionary<TKey, TValue>
    • HashSet<T>
    • Queue<T> un Stack<T>
    • citas klases no System.Collections un System.Collections.Generic telpām
  • virknes (System.String - iterējas pa simboliem)
  • objekti, kas atgriež LINQ vaicājumus
  • pašu datu tipu, kas īsteno kādu no minētajām saskarnēm.

Piemērs:

// Masīvs
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> iterē pa 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
}

// Paštaisīta klase, kas īsteno 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; // Iteratora izmantošana
        }
    }

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

// Pašas klases izmantošana
MyCollection myCollection = new MyCollection();
foreach (int item in myCollection)
{
    // ...
}