Posterous theme by Cory Watilo

NameValue, now with Distinct() support

One of the more useful little classes in my utility box is NameValue. It's so very easy to fill with useful data from a Linq query, and once filled so easy to move between layers, in a way that a projection simply can't be used. The simple little NameValue class bind just fine to a drop down menu, and will bring you tea after you finish with that stupid girl that didn't like your pony/monkey chimera.

I recently had to add equality checks and an override for == and != in order to make merging two lists of name value pairs together possible. Now .Distinct() works on a List<NameValue>! There's some good material out there for how to make a quality equality implementation.

[Serializable] public class NameValue { public object Name { get { return _Name; } set { _Name = value; } } protected virtual object _Name { get; set; } public object Value { get { return _Value; } set { _Value = value; } } protected virtual object _Value { get; set; } public override bool Equals(object obj) { if (obj == null) return false; if (this.GetType() != obj.GetType()) return false; // safe because of the GetType check NameValue nv = (NameValue)obj; // use this pattern to compare reference members if (!Object.Equals(this.Value, nv.Value)) return false; if (!Object.Equals(this.Name, nv.Name)) return false; return true; } public override int GetHashCode() { return Name.GetHashCode() ^ Value.GetHashCode(); } public static bool operator ==(NameValue n1, NameValue n2) { return n1.Equals(n2); } public static bool operator !=(NameValue n1, NameValue n2) { return !n1.Equals(n2); } }