Another set I use quite often is for coalescing IDictionary methods:
public static TValue Get<TKey, TValue>(this IDictionary<TKey, TValue> d, TKey key, Func<TValue> valueThunk)
{
TValue v = d.Get(key);
if (v == null)
{
v = valueThunk();
d.Add(key, v);
}
return v;
}
public static TValue Get<TKey, TValue>(this IDictionary<TKey, TValue> d, TKey key, TValue coalesce)
{
return Get(d, key, () => coalesce);
}
And for working with collections in general:
public static IEnumerable<T> AsCollection<T>(this T item)
{
yield return item;
}
Then for tree-like structures:
public static LinkedList<T> Up<T>(this T node, Func<T, T> parent)
{
var list = new LinkedList<T>();
node.Up(parent, n => list.AddFirst(n));
return list;
}
So I can then easily traverse and operate upon a up a class like:
class Category
{
public string Name { get; set; }
public Category Parent { get; set; }
}
Next, to facilitate function composition and a more F# like way of programming in C#:
public static Func<T, T> Func<T>(this Func<T, T> f)
{
return f;
}
public static Func<T1, R> Compose<T1, T2, R>(this Func<T1, T2> f, Func<T2, R> g)
{
return x => g(f(x));
}