The Insanity Beyond Null, Exercise 1

CSharp · Console

/Program.cs

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

public sealed class Program
{
    public sealed class Node
	{
        private readonly string name;

        public Node(string name)
            : this(name, Array.Empty<string>())
		{
        }

        public Node(string name, params string[] childNodes)
			: this(name, childNodes.Select(s => new Node(s)).ToImmutableList())
		{
        }

        private Node(string name, IEnumerable<Node> childNodes)
		{
            this.name = name;
            ChildNodes = childNodes;
        }

        public IEnumerable<Node> ChildNodes { get; }

        public override string ToString()
		{
            return $"{nameof(name)}: {name}";
        }
    }

    private static IEnumerable<Node> Nodes { get; } = new[]
	{
		new Node("image", "raw", "jpeg", "png"),
		new Node("video", "mp4"),
		new Node("game"),
		new Node("music", "wav", "mp3"),
	};

    private static void FixMe()
	{
        var list = Nodes
            // Defers disposition of 'null' when 'ChildNodes' is empty
			.Select(n => n.ChildNodes.FirstOrDefault())
            .Where(n => n is {});
		foreach (var n in list)
		{
			Console.WriteLine(n);
		}
    }

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