Menu
CoddyTech

OrderBy and Take

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

OrderBy sorts a collection by a key you pick with a lambda, smallest first, and OrderByDescending sorts biggest first. Items with equal keys keep their original order. ThenBy adds a second key for ties. Take(n) keeps the first n items, or all of them when there are fewer, and Skip(n) drops the first n.

var podium = players
    .OrderByDescending(p => p.Score)
    .Take(2)
    .Select((p, i) => $"{i + 1}. {p.Name} {p.Score}");

With Ada at 40, Linus at 72 and Grace at 55, podium holds 1. Linus 72 and 2. Grace 55. This Select takes a lambda with two parameters: the item and its position, starting at 0.

challenge icon

Challenge

Easy

Add a top command that shows the biggest expenses.

  1. Add case "top": above default:. Start with var howMany = 3;
  2. When there is a second word, parse it into howMany with int.TryParse. When that fails, write Invalid number: abc (with the word given) to stderr and return 1;.
  3. Sort the expenses biggest amount first, take howMany of them, and print each with its rank, starting at 1. With the three expenses in expenses.json, dotnet run -- top 2 prints:
    1. Groceries: 31.80 (food)
    2. Lunch: 12.50 (food)

Try it: the terminal beside the editor already reads dotnet run -- top 2, so press Run: the two lines above. Change the arguments to top alone and Run again: three lines. Raise Train's amount in expenses.json to 40 and Run: 1. Train: 40.00 (travel) comes first.

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;
        case "list":
            var shown = args.Length > 1 ? expenses.Where(e => e.Category == args[1]).ToList() : expenses;
            if (shown.Count == 0)
            {
                Console.WriteLine("No expenses.");
                break;
            }
            foreach (var line in shown.Select(e => $"{e.Name}: {e.Amount:F2} ({e.Category})"))
            {
                Console.WriteLine(line);
            }
            break;
        default:
            Console.Error.WriteLine($"Unknown command: {args[0]}");
            return 1;
    }
}
return 0;

All lessons in C# and .NET Basics