C#C# · Lesson 7 of 9

LINQ & Async/Await

LINQ is what makes C# shine for data manipulation. async/await is what makes C# shine for I/O. Together they're unstoppable.

C#
using System.Linq;
using System.Net.Http;
using System.Text.Json;

// LINQ examples
int[] numbers = Enumerable.Range(1, 20).ToArray();

var evenSquares = numbers
    .Where(n => n % 2 == 0)
    .Select(n => n * n)
    .ToList();

Console.WriteLine(string.Join(", ", evenSquares));
// 4, 16, 36, 64, 100, 144, 196, 256, 324, 400

// Group by
string[] words = { "apple", "ant", "bear", "banana", "cat", "cherry" };
var grouped = words.GroupBy(w => w[0]);
foreach (var group in grouped) {
    Console.WriteLine($"{group.Key}: {string.Join(", ", group)}");
}
// a: apple, ant
// b: bear, banana
// c: cat, cherry

// Order by multiple fields
var people = new[] {
    new { Name = "Alice", Age = 30 },
    new { Name = "Bob", Age = 25 },
    new { Name = "Carol", Age = 30 },
};
var sorted = people.OrderBy(p => p.Age).ThenBy(p => p.Name);
foreach (var p in sorted) {
    Console.WriteLine($"{p.Name}: {p.Age}");
}
C#
// async/await — non-blocking I/O
using System.Net.Http;
using System.Net.Http.Json;

async Task<string> FetchAsync(string url) {
    using var client = new HttpClient();
    return await client.GetStringAsync(url);
}

async Task<T?> FetchJsonAsync<T>(string url) {
    using var client = new HttpClient();
    return await client.GetFromJsonAsync<T>(url);
}

// Run multiple tasks in parallel
async Task Main() {
    var tasks = new[] {
        FetchAsync("https://httpbin.org/get"),
        FetchAsync("https://httpbin.org/ip"),
    };

    string[] results = await Task.WhenAll(tasks);
    foreach (var result in results) {
        Console.WriteLine(result[..100]);  // first 100 chars
    }
}

await Main();
◆ Note
In C# console apps with top-level statements, you can use await directly at the top level. In older style code, the Main method must be async Task Main(). Either way, async/await is the standard for any I/O operation.