iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Loops

C# ships for, foreach, while, do-while, plus LINQ for query-style iteration. Use foreach by default; switch to for when you need the index.

Every C# loop + LINQ patterns

EXAMPLE
var xs = new[] { 10, 20, 30, 40, 50 };

// 1) Classic for
for (var i = 0; i < xs.Length; i++) Console.WriteLine($"{i}: {xs[i]}");

// 2) foreach
foreach (var n in xs) Console.WriteLine(n);

foreach (var (key, value) in new Dictionary<string, int> { ["a"] = 1, ["b"] = 2 })
    Console.WriteLine($"{key}={value}");

// 3) while + do-while
var n = 0;
while (n < 5) n++;

// 4) Async iteration — await foreach
public async IAsyncEnumerable<int> StreamCountAsync() {
    for (var i = 0; i < 10; i++) {
        await Task.Delay(100);
        yield return i;
    }
}
await foreach (var v in StreamCountAsync()) Console.WriteLine(v);

// 5) Range / Index — slicing
foreach (var v in xs[1..^1]) Console.WriteLine(v);   // skip first + last

// 6) LINQ — query syntax
var evens = from x in xs where x % 2 == 0 select x;
var total = (from x in xs select x).Sum();

// Method syntax
var evens2 = xs.Where(x => x % 2 == 0).ToList();
var total2 = xs.Sum();
var max    = xs.Max();
var groups = users.GroupBy(u => u.Role).ToDictionary(g => g.Key, g => g.Count());
var joined = users.Join(orders, u => u.Id, o => o.UserId, (u, o) => new { u.Name, o.Total });

// 7) parallel
Parallel.ForEach(xs, n => Process(n));
var squared = xs.AsParallel().Select(n => n * n).ToList();

// 8) Performance — Span<T> avoids allocations
ReadOnlySpan<char> span = "hello world".AsSpan();
foreach (var c in span) Console.Write(c);

Why it matters

LINQ + foreach handle 95% of loops in modern C#. Reach for explicit for when you need raw indexing perf or are reading from a span / array directly.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
for (int i = 0; i < 3; i++) Console.WriteLine(i);

foreach (var s in new[] {"a","b"}) Console.WriteLine(s);

int n = 0;
while (n < 3) { Console.WriteLine(n); n++; }
Try it Yourself »

Discussion

Loading…