After looking over some questions on StackOverflow it got me thinking about extension methods. It's not really something which I have looked into much as I only use Visual Studio 2008 at home for personal projects. I stumbled upon one post about potential extension methods to add to a colaboration on CodePlex for everyones use. I was scrolling through some of the potentials to be submitted and came across this post. It intrigued me as the main method was converting an IEnumerable
However the way they were doing it was the usual "go through all the items, add the separator after everyone, then at the end take the last off". Personally when I see this I get a little sad. It's just not very elegant but also it means you don't harness the power of the framework ... which is what it is there for!
Side Note With the advent of .net 2.0 Generics was brought in. This opened up a whole world of fun for developers and a lot of useful things especially around the area of collections. If you've not looked at Generics I would highly recommend working your Google-Fu and doing some reading.
Anyway ... using generics I decided to refactor the ToString method for IEnumerable to use ToArray() of a List
public static string ToString<T>(this IEnumerable<T> collection,
Func<T, string> stringElement, string separator){List<string> result = new List<string>();foreach (T item in collection){result.Add(stringElement(item));}return string.Join(separator, result.ToArray());}
public static IEnumerable<T> ExecuteForEach<T>(this IEnumerable<T> collection,
Func<T, T> function){List<T> result = new List<T>();foreach (T item in collection){result.Add(function(item));}return result.AsEnumerable();}
public static IEnumerable<U> ExecuteForEach<T, U>(this IEnumerable<T> collection,
Func<T, U> function){List<U> result = new List<U>();foreach (T item in collection){result.Add(function(item));}return result.AsEnumerable();}
With using the updated ExecuteForEach<T, U> (I decided on calling it ExecuteForEach as it will update / perform a function on each of the items in the collection and update them, not just perform an function on them) we can now update the ToString method call to be just two lines; it abstracts the looping away into a different function which can be used again for different actions, but also uses the power of the framework with the string.join functionality.
public static string ToString<T>(this IEnumerable<T> collection,
Func<T, string> stringElement, string separator){List<string> possible = collection
.ExecuteForEach(t => stringElement(t))
.ToList();return string.Join(separator, possible.ToArray());}
public static string ToString<T>(this IEnumerable<T> collection, string separator){return ToString(collection, t => t.ToString(), separator);}
[TestMethod]public void ToStringTest(){var ints = new int[] { 1, 2, 3 };var result = ints.ToString(", ");Assert.AreEqual("1, 2, 3", result);}
No comments:
Post a Comment