Aug 7, 2015

Get number of flags from an enum variable


Code:
public static class EnumHelper 
{
    public static UInt32 NumFlags(this Enum e)
    {
        UInt32 v = Convert.ToUInt32(e);
        v = v - ((v >> 1) & 0x55555555);
        v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
        UInt32 count = ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
        return count;
    }
}

This is some kind of black magic, works very fast. Got here.

Lazy struct

Code:
    struct Lazy<T>
    {
        T value;
        bool init;
        Func<T> factory;

        public Lazy(Func<T> f)
        {
            factory = f;
            init = false;
            value = default(T);
        }

        public T Value
        {
            get
            {
                if (init) return value;
                else
                {
                    init = true;
                    return value = factory();
                }
            }
        }
    }


Variant with a single argument
is useful when we want to use a non-local function and don't want to use closure (for better performance)

Code:
    struct Lazy<TVal, TArg>
    {
        TVal value;
        TArg arg;
        bool init;
        Func<TArg, TVal> factory;

        public Lazy(Func<TArg, TVal> f, TArg arg)
        {
            factory = f;
            init = false;
            value = default(TVal);
            this.arg = arg;
        }

        public TVal Value
        {
            get
            {
                if (init) return value;
                else
                {
                    init = true;
                    return value = factory(arg);
                }
            }
        }
    }

May 19, 2015

Linq TakeBy

I was about to write such an extension
But then desided to google for it first, and voila:

Code:
/// <summary>
/// <paramref name="source"/>中の要素を<paramref name="count"/>
/// 個ごとにまとめ直します。
/// 最後の要素数が足りない場合は足りないまま返します。
/// </summary>
public static IEnumerable<IEnumerable<TSource>> TakeBy<TSource>(this IEnumerable<TSource> source, int count)
{
    if (source == null)
    {
        throw new ArgumentNullException("source");
    }
    if (count < 1)
    {
        throw new ArgumentOutOfRangeException("count");
    }
    while (source.Any())
    {
        yield return source.Take(count);
        source = source.Skip(count);
    }
}

got it here
Isn't it nice?

ps: this variant is much faster

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)