One useful thing is to be able to concatenate IEnumerable's into a string for printing. A couple extension methods take care of this.
public static string ToString<T>(this IEnumerable<T> collection) { return collection.ToString(","); } public static string ToString<T>(this IEnumerable<T> collection, string separater) { return String.Join(",", collection); } public static string ToString<T>(this IEnumerable<T> collection, Func<T, object> field) where T : class { return collection.ToString(",", field); } public static string ToString<T>(this IEnumerable<T> collection, string separater, Func<T, object> field) where T : class { return String.Join(separater, collection.Select(field)); }
But couldn't we just use String.Join as the extension methods are? Sure, but this is more fun and provides a more logical response to ToString() as well as more control over objects with anonymous functions.
var testList = new List<SimpleObject>() { new SimpleObject() { Id = 1, Name = "asdf" }, new SimpleObject() { Id = 2, Name = "qwer" }, new SimpleObject() { Id = 3, Name = "zxcv" }, }; var s = testList.ToString<SimpleObject>(",", c => c.Id);
One caveat, the base IEnumerable.ToString() is still there, and simple prints out something like System.Collections.Generic.... Not what we expect. To call the basic extension method, we have to specify it with the type parameter:
var fail = testList.ToString(); // Ruh-roh! var works = testList.ToString<SimpleObject>(); // Woot!
No comments:
Post a Comment