C# Intermediate Introduction
C# Intermediate is the second band of C#. It deepens the beginner topics with delegates, LINQ, generics, and async basics.
A hand loop totals passing scores
A loop adds each score above the pass mark. This is the way the beginner course already writes it.
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
List<int> scores = new List<int> { 45, 82, 67, 91, 38 };
int total = 0;
foreach (int score in scores)
{
if (score > 50)
{
total = total + score;
}
}
Console.WriteLine("Total: " + total);
}
}The same total from a query
This snippet is a preview of LINQ query syntax. Later lessons explain each part in full.
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
List<int> scores = new List<int> { 45, 82, 67, 91, 38 };
IEnumerable<int> passing = from score in scores
where score > 50
select score;
int total = 0;
foreach (int score in passing)
{
total = total + score;
}
Console.WriteLine("Total: " + total);
}
}Example
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
List<int> scores = new List<int> { 30, 75, 60, 95 };
IEnumerable<int> passing = from score in scores
where score > 50
select score;
int count = 0;
int total = 0;
foreach (int score in passing)
{
count = count + 1;
total = total + score;
}
Console.WriteLine("Count: " + count);
Console.WriteLine("Total: " + total);
}
}Key points
- Delegates and lambdas pass methods around as values.
- LINQ queries collections with a short readable form.
- Generics let one class or method work with many types.
- Collections lessons cover sets, queues, stacks, and dictionaries in depth.
- Strings and files lessons cover building text and saving it to disk.
- Exceptions lessons cover filtered catches and custom error types.
- Records and patterns lessons cover value-based types and matching shapes.
- Async lessons cover tasks that run without blocking the program.
In this example, the query keeps the scores above 50. The loop counts three passing scores. The loop also adds them to a total of 230.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does the preview query select?