mandag 9. november 2009

Sort your Arrays

Sometimes simple things get complex and visa/versa. I've done sorting of arrays many times. Finally it struck me. I've been wasting time again... Just define you sorting algoritm in the CompareTo method. Never return any default values like 1, 0 or -1. It will make you code fail...

public class Item : IComparable<item>
{
   
    public Item(int id, string name)
    {
        Id = id;
        Name = name;
    }

    public int Id
    { get; set; }

    public string Name
    {get; set;}

    public string[] Email
    { get; set; }

    public int CompareTo(Item item)
    {
        var compare = Name.CompareTo(item.Name);
        if (compare != 0)
            return compare;

        return Id.CompareTo(item.Id);
    }
}

Now I test my code...

[Test]
public void SortArray()
{
var array = new[] {new Item(1, "B"), new Item(2, "C"), new Item(3, "A")};

Array.Sort(array);

Assert.AreEqual(array[0].Name, "A");
Assert.AreEqual(array[1].Name, "B");
Assert.AreEqual(array[2].Name, "C");
}

XmlSerializer

Every project these days tend to deal with some kind of serialization. I've Created a small pice of code to make my world simpler. How to create a Generic XmlSerializer.
public static class GenericXmlSerializer { public static T Deserialize(string xml) { var serializer = new XmlSerializer(typeof(T)); using (var sr = new StringReader(xml)) { return (T)serializer.Deserialize(sr); } } public static string Serialize(T source) { var serializer = new XmlSerializer(typeof(T)); using (var sr = new StringWriter()) { serializer.Serialize(sr, source); return sr.ToString(); } } }
My next problem is how to run my code. I've created a small example class for my example
public class Item
  {
  public string Name
  {get; set;}

  [XmlElement]
  public string[] Email
  { get; set; }

}
My production code for serialize/deserialize an instance of Item is displayed below.
--Serialize
var item = new Item {Name = "Authovr", Email = new string[] {"author1@gmail.com", "author2@gmail.com"}};
var xml = GenericXmlSerializer.Serialize(item);
--Deserialize
var xml = "<item><name>Author</name><email>author1@gmail.com</email><email>author2@gmail.com</email></item>";
var item = GenericXmlSerializer.Deserialize(xml);
Note!!
My example includes serializing an Array element. Using the XmlElement atteribute makes the serialization nice and readable.