My last post, 'more fun with yield return' described a simple method I'd added to a Contact class to iterate its properties (all strings) and only return those that were not null or empty. It was a nice use of the 'yield return' statement to build a custom iterator. I got a good comment from Ken Egozi who thought that I was putting UI code in my entity. He's right of course, the entity is not the right place for stuff like this. So I started thinking about creating a UI method to build the list and then a generic UI method for building a list of any entity's properties. It was getting pretty funky, with LineBuilder<T> and all kinds of crazy functional stuff, but a couple of refactorings later and all my code evaporated leaving just an array initializer and a Linq Where clause. How about this...
using System; using System.Linq; namespace Mike.PropertyRenderer { class Program { static void Main(string[] args) { var contact = new Contact { Firstname = "Mike", Lastname = "Hadlow", Address1 = "3 Nicely Avenue", Country = new Country { Name = "UK" } }; foreach (var s in new []{ contact.Firstname, contact.Lastname, contact.Address1, contact.Address2, contact.Address3, contact.Town, contact.County, contact.Postcode, contact.Country.Name} .Where(line => !string.IsNullOrEmpty(line))) { Console.WriteLine(s); } Console.ReadLine(); } } public class Contact { public string Firstname { get; set; } public string Lastname { get; set; } public string Address1 { get; set; } public string Address2 { get; set; } public string Address3 { get; set; } public string Town { get; set; } public string County { get; set; } public string Postcode { get; set; } public Country Country { get; set; } } public class Country { public string Name { get; set; } } }
gives this:
I've definitely spent enough time on this now :P
1 comment:
If you're formatting value objects for the UI, how about serialising to hCard? You can go on forever with this stuff..
Post a Comment