IEnumerable क्या है
IEnumerable यह promise है कि किसी चीज़ को एक-एक item करके चला जा सकता है। यह promise रखने वाली कोई भी चीज़ एक foreach loop में उपयोग की जा सकती है।
In this page:
Syntax
class ClassName : IEnumerable<type>
{
public IEnumerator<type> GetEnumerator()
{
yield return item;
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
IEnumerable
IEnumerable<T> वह interface है जो किसी type को इसके elements पर एक enumerator पाने का तरीका उजागर करके foreach loop में उपयोग करने योग्य बनाता है।
Arrays, List<T>, और Dictionary<K,V> सब इसे implement करते हैं। आप इसे किसी custom collection type पर खुद yield return का उपयोग करके lazily elements produce करने के लिए implement कर सकते हैं।
Note:
IEnumerable<T> return करने वाले किसी method के अंदर yield return बिना manually IEnumerator implement किए एक iterator बनाता है।उदाहरण: IEnumerable
using System;
using System.Collections;
using System.Collections.Generic;
class Countdown : IEnumerable<int>
{
private int start;
public Countdown(int start) { this.start = start; }
public IEnumerator<int> GetEnumerator()
{
for (int i = start; i >= 0; i--)
{
yield return i;
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
class Program
{
static void Main(string[] args)
{
foreach (int n in new Countdown(3))
{
Console.WriteLine(n);
}
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- किसी collection को enumerate करते समय modify करना, जो
InvalidOperationExceptionफेंकता है। - किसी lazy
IEnumerableको कई बार enumerate करना और काम दोहराना। yield returnभूल जाना और पूरी collection को एक साथ return करना।
चैप्टर सारांश
- Interfaces एक contract define करते हैं जिसे classes implement करती हैं, और एक class कई interfaces implement कर सकती है।
- Default interface methods optional implementations प्रदान करते हैं।
IComparableऔरIEnumerablesorting और iteration के लिए आम interfaces हैं।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: