foreach Loop कैसे लिखें
एक foreach loop किसी collection के हर item को एक-एक करके visit करता है, जैसे एक teacher किसी row में हर student को एक sheet दे रही हो। आपको कभी positions गिनने की ज़रूरत नहीं।
In this page:
Syntax
foreach (type item in collection)
{
// use item
}
foreach Loop
foreach बिना manual index tracking के किसी collection के हर element पर iterate करता है, IEnumerable implement करने वाली किसी भी type के साथ काम करते हुए।
यह arrays, lists, और दूसरी collections को process करने का सबसे सुरक्षित और readable तरीका है। आप items skip करने के लिए loop variable को modify नहीं कर सकते — उसके लिए indexed access उपयोग करें।
Note:
जब आपको index की ज़रूरत न हो तो
for से foreach को प्राथमिकता दें।उदाहरण: foreach Loop
using System;
class Program
{
static void Main(string[] args)
{
string[] fruits = { "apple", "banana", "cherry" };
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
}
}
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. #}
आम गलतियां
- किसी
foreachके अंदर collection को modify करना, जोInvalidOperationExceptionफेंकता है। - loop variable को assign करने की कोशिश करना, जो
foreachमें read-only है। - किसी null collection पर
foreachउपयोग करना, जोNullReferenceExceptionफेंकता है।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: