public static void TestLabelTree() { var labelTree = new LabelTree( "Animals", List( new LabelTree( "Birds", List(new LabelTree("Crow"), new LabelTree("Eagle")) ), new LabelTree( "Mammals", List(new LabelTree("Dog"), new LabelTree("Cat")) ) ) ); var germanDictionary = new System.Collections.Generic.Dictionary <string, string> { ["Animals"] = "Tiere", ["Birds"] = "Vögel", ["Mammals"] = "Säugetiere", ["Crow"] = "Krähe", ["Eagle"] = "Adler", ["Dog"] = "Hund", ["Cat"] = "Katze" }; var actual = labelTree.Map(l => germanDictionary[l]); var expected = new LabelTree( "Tiere", List( new LabelTree( "Vögel", List(new LabelTree("Krähe"), new LabelTree("Adler")) ), new LabelTree( "Säugetiere", List(new LabelTree("Hund"), new LabelTree("Katze")) ) ) ); Assert.AreEqual(expected, actual); }
public static LabelTree <R> Map <T, R>(this LabelTree <T> @this, Func <T, R> f) => new LabelTree <R>(f(@this.Label), @this.Children.Map(tree => tree.Map(f)));
// Imagine you need to add localization to your navigation tree: you're given a `LabelTree` where // the value of each label is a key, and a dictionary that maps keys // to translations in one of the languages that your site must support // (hint: define `Map` for `LabelTree` and use it to obtain the localized navigation/category tree) static LabelTree Map(this LabelTree tree, Func <string, string> f) => new LabelTree(f(tree.Label), tree.Subtrees.Map(t => t.Map(f)));