Oct 22, 2014

Easy hierarchy traversal w/o recursion

    class Program
    {
        static void Main(string[] args)
        {
            Node n1 = new Node(null, "1. table");
            Node n2 = new Node(null, "2. chair");
            Node n11 = new Node(n1, "1.1. teapot");
            Node n12 = new Node(n1, "1.2. cup");
            Node n121 = new Node(n12, "1.2.1. tea");
            Node n21 = new Node(n2, "2.1. man");
 
            var topLevel = new Node[] { n1, n2 };
            var flat = Traverse(topLevel);
            foreach (var n in flat.OrderBy(n=>n.name))
            {
                Console.WriteLine(new string('\t', n.level) + n.name);
            }
            Console.ReadLine();
        }
 
        static IEnumerable<Node> Traverse(IEnumerable<Node> top)
        {
            Stack<Node> s = new Stack<Node>(top);
            while (s.Count > 0)
            {
                var next = s.Pop();
                yield return next;
                foreach (var n in next.nodes)
                {
                    s.Push(n);
                }
            }
        }
    }
 
    class Node
    {
        public int level;
        public List<Node> nodes = new List<Node>();
        public string name;
        public Node(Node parent, string name)
        {
            this.name = name;
            if (parent != null)
            {
                parent.nodes.Add(this);
                level = parent.level + 1;
            }
            else
            {
                level = 0;
            }
        }
    }


Oct 16, 2014

Delegates act as value types

Action a1 = () => Console.Write("1 ");
Action a2 = () => Console.Write("2 ");
Action tmp = a1;
a1 += a2;
a2 = tmp;
Console.Write("a1:\t");
a1();   //1 2
Console.Write("\na2:\t");
a2();   //1
Console.ReadLine();

its because delegates are immutable, just like strings.
a1 += a2 is a shugar for a1 = (Action)Delegate.Combine(a1, a2)