Junior
Koji objekti mogu biti korišćeni u foreach petlji?
sobes.tech АИ
Одговор од АИ
U petlji foreach mogu se koristiti objekti koji implementiraju sučelje System.Collections.IEnumerable ili System.Collections.Generic.IEnumerable<T>.
Glavne vrste objekata:
- Nizovi (jednodimenzionalni i višedimenzionalni)
- Kolekcije koje implementiraju
IEnumerableiliIEnumerable<T>:List<T>Dictionary<TKey, TValue>HashSet<T>Queue<T>iStack<T>- Ostale klase iz prostora imena
System.CollectionsiSystem.Collections.Generic
- Nizovi znakova (
System.String- iterira se po znakovima) - Objekti koji se vraćaju LINQ upitima
- Vlastiti tipovi podataka koji implementiraju jedan od navedenih sučelja.
Primjer:
// Niz
string[] colors = {"crvena", "zelena", "plava"};
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 = "zdravo";
foreach (char c in text)
{
// ...
}
// Dictionary<TKey, TValue> iterira preko 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
}
// Vlastiti razred koji implementira 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; // Korištenje iteratora
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
// Korištenje vlastitog razreda
MyCollection myCollection = new MyCollection();
foreach (int item in myCollection)
{
// ...
}