← Back to Tutorials Chapter 9

Advanced Topics

LINQ (Language Integrated Query)

LINQ allows querying collections with SQL-like syntax or method chains.

using System.Linq;
int[] numbers = { 5, 2, 8, 1, 9, 3 };

// Query syntax
var evenQuery = from n in numbers
                where n % 2 == 0
                orderby n
                select n;

// Method syntax
var evenMethod = numbers.Where(n => n % 2 == 0)
                        .OrderBy(n => n)
                        .ToList();

// Common LINQ methods
numbers.Where(n => n > 5);
numbers.Select(n => n * 2);
numbers.OrderBy(n => n);
numbers.GroupBy(n => n % 2);
numbers.Average();
numbers.Sum();
numbers.Min(); numbers.Max();

Delegates

// Action - no return value
Action log = msg => Console.WriteLine(msg);
log("Hello from delegate");

// Func - returns a value
Func add = (a, b) => a + b;
int result = add(5, 3);

Generics

List names = new List();
names.Add("Alice");
names.Add("Bob");
names.Remove("Alice");

Dictionary scores = new();
scores["Alice"] = 95;
scores["Bob"] = 87;

Queue queue = new Queue();
queue.Enqueue("First");
string next = queue.Dequeue();

Stack stack = new Stack();
stack.Push(1);
int top = stack.Pop();

Async/Await

async Task FetchDataAsync() {
    using HttpClient client = new HttpClient();
    string result = await client.GetStringAsync("https://api.example.com");
    return result;
}

// Call async method
string data = await FetchDataAsync();

Nullable Types

int? maybeNumber = null;
if (maybeNumber.HasValue) {
    Console.WriteLine(maybeNumber.Value);
}
int actual = maybeNumber ?? 0;  // Null-coalescing
int length = name?.Length ?? 0; // Null-conditional
C# advanced topics

Practice Task

Write a C# program that applies the concepts covered in this chapter. Experiment with different inputs and test your understanding.