Some Extension Methods
Tuesday, October 20, 2009 8:52 AM
These extension methods are becoming a staple in every project of mine. I just wanted to archive them and put them in a place I could easily point to.
public static IEnumerable<T> Each<T>(this IEnumerable<T> source, Action<T> action)
{
source = source.ToArray();
foreach (var item in source) action(item);
return source;
}
public static IEnumerable<T> TryEach<T>(this IEnumerable<T> source, Action<T> action, Action<Exception, T> onError)
{
return source.Each(item => item.Try(action, onError));
}
public static void Try<T>(this T item, Action<T> action, Action<Exception, T> onError)
{
try
{
action(item);
}
catch (Exception ex)
{
if (onError != null) onError(ex, item);
}
}
public static T As<T>(this object source)
{
return (T)source;
}
public static T FindById<T>(this Control control, string id) where T : Control
{
return (T)control.FindControl(id);
}
public static string F(this string source, object arg0)
{
return string.Format(source, arg0);
}
public static string F(this string source, object arg0, object arg1)
{
return string.Format(source, arg0, arg1);
}
public static string F(this string source, object arg0, object arg1, object arg2)
{
return string.Format(source, arg0, arg1, arg2);
}
public static string F(this string source, params object[] args)
{
return string.Format(source, args);
}
Tags: .net