Memoize<T, TResult>

public static Func<T, TResult> Memoize<T, TResult>(this Func<T, TResult> func)
        {
            var t = new Dictionary<T, TResult>();
            return n =>
            {
                if (t.ContainsKey(n)) return t[n];
                else
                {
                    var result = func(n);
                    t.Add(n, result);
                    return result;
                }
            };
        }
Example:
 Func<string, string> format = new Func<string, string>(s =>
        {
            // a long running operation
            System.Threading.Thread.Sleep(2000);
            return String.Format("hello {0}", s);
        }).Memoize();
        // takes 2000 ms
        foreach (var item in Enumerable.Range(0, 100))
        {
            Response.WriteLine(format(" world"));
        }

Description

Memoize afunction

Details

Double click on the code to select all.

 

;