The Insanity Beyond Null, Exercise 2 [sample fix]

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;

public static class Program {

    private static readonly ImmutableDictionary<string, Action> CommandMap
		= new Dictionary<string, Action>()
		{
			["help"] = () => PrintHelp(),
			["quit"] = () => ExitProgram(),
			["shutdown"] = () => ShutdownSystem(),
		}.ToImmutableDictionary();

    private static void PrintHelp() => Console.WriteLine($"{nameof(PrintHelp)}");
    private static void ExitProgram() => Console.WriteLine($"{nameof(ExitProgram)}");
    private static void ShutdownSystem() => Console.WriteLine($"{nameof(ShutdownSystem)}");

    private static IEnumerable<string> CommandList { get; }
		= new[] { "help", "reboot", "shutdown" };

    private static void FixMe()
	{
		var list = CommandList.SelectMany(n => CommandMap.TryGetValue(n, out var action)
										  ? new[] { action }
										  : Enumerable.Empty<Action>());
		
        // The next is also fine, but the number of elements differs:
		//
    	// var list = CommandList.Select(n => CommandMap.TryGetValue(n, out var action)
		//     ? action
		//     : () => {});

		foreach (var action in list)
		{
			action();
		}
    }

    public static void Main(string[] args)
	{
        FixMe();
    }
}
;