Menu
CoddyTech

Where and Select

Part of the C# and .NET Basics section of Coddy's ASP.NET Core journey. Lesson 10 of 20.

LINQ is a set of methods that query any collection. Each takes a lambda, a small function written x => ..., and calls it for every item. Where keeps the items for which the lambda returns true. Select turns each item into something new.

var temps = new List<int> { 18, 25, 31, 22 };
var hot = temps.Where(t => t > 24);
var labels = hot.Select(t => $"{t} degrees");
Console.WriteLine(string.Join(", ", labels));

This prints 25 degrees, 31 degrees. A query is lazy: it runs when something reads its items, such as foreach, string.Join or ToList(). ToList() runs it once and keeps the result as a List<T>. The SDK's implicit usings already include System.Linq.

challenge icon

Challenge

Easy

Add a list command that prints the saved expenses, all of them or one category.

  1. Add case "list": above default:.
  2. With a category (list food), use Where to keep the expenses of that category, then ToList(). Without one (list), use all of expenses.
  3. When nothing is left, print No expenses. and break;.
  4. Otherwise use Select to turn each expense into a line, in the order they were saved, and print each line. With the three expenses in expenses.json, dotnet run -- list food prints:
    Lunch: 12.50 (food)
    Groceries: 31.80 (food)

Try it: the terminal beside the editor already reads dotnet run -- list food, so press Run: the two lines above. Change the arguments to list rockets and Run again: No expenses. Then put back list food, change Train's category in expenses.json to food and Run: three lines.

Try it yourself

using System.Globalization;
using System.Text.Json;

var file = "expenses.json";
var expenses = new List<Expense>();
if (File.Exists(file))
{
    expenses = JsonSerializer.Deserialize<List<Expense>>(File.ReadAllText(file)) ?? new List<Expense>();
}
var count = expenses.Count;
var total = expenses.Sum(e => e.Amount);

if (args.Length == 0)
{
    Console.WriteLine("Expense Tracker");
    Console.WriteLine($"{count} expenses");
    Console.WriteLine($"Total: {total:F2}");
}
else
{
    switch (args[0])
    {
        case "add":
            if (args.Length < 3)
            {
                Console.Error.WriteLine("Usage: add <name> <amount> [category]");
                return 1;
            }
            if (!decimal.TryParse(args[2], CultureInfo.InvariantCulture, out var amount))
            {
                Console.Error.WriteLine($"Invalid amount: {args[2]}");
                return 1;
            }
            var category = args.Length > 3 ? args[3] : "other";
            var expense = new Expense(args[1], amount, category);
            expenses.Add(expense);
            File.WriteAllText(file, JsonSerializer.Serialize(expenses));
            Console.WriteLine($"Added {expense.Name}: {expense.Amount:F2} ({expense.Category})");
            break;
        case "remove":
            if (args.Length < 2)
            {
                Console.Error.WriteLine("Usage: remove <name>");
                return 1;
            }
            Expense? match = expenses.Find(e => e.Name == args[1]);
            if (match is null)
            {
                Console.Error.WriteLine($"No expense named {args[1]}.");
                return 1;
            }
            expenses.Remove(match);
            File.WriteAllText(file, JsonSerializer.Serialize(expenses));
            Console.WriteLine($"Removed {match.Name}: {match.Amount:F2}");
            break;
        default:
            Console.Error.WriteLine($"Unknown command: {args[0]}");
            return 1;
    }
}
return 0;
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in C# and .NET Basics