Tuesday, July 29, 2008

There's usually an easier way

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 []{
               .Where(line => !string.IsNullOrEmpty(line)))


   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:

Ed said...

If you're formatting value objects for the UI, how about serialising to hCard? You can go on forever with this stuff..