Skip to content

Instantly share code, notes, and snippets.

@AlexZeitler
Created April 27, 2011 20:51
Show Gist options
  • Select an option

  • Save AlexZeitler/945176 to your computer and use it in GitHub Desktop.

Select an option

Save AlexZeitler/945176 to your computer and use it in GitHub Desktop.
rudimentary draft of comparing items of two lists on specified property as machine.specfication extension method
public class Given_two_lists_containing_a_point_each_when_comparing_points_on_x_value {
static IList<Point> _expectedPoints;
static IList<Point> _actualPoints;
Establish context
= () => {
_expectedPoints = new List<Point>
{
new Point {X = 153.6m, Y = 21m, Z = 0}
};
_actualPoints = new List<Point>
{
new Point {X = 6*4*8.00m*0.8m, Y = 20m, Z = 0}
};
};
It should_yield_equality_on_x_value
= () => {
_actualPoints.ShouldEqualItemsOn(_expectedPoints, p => p.X);
};
}
public static class ShouldExtensions {
public static void ShouldEqualItemsOn<T, TProperty>(this IEnumerable<T> actual, IEnumerable<T> expected, Expression<Func<T, TProperty>> propertyExpression) {
PropertyInfo propertyInfo = ((MemberExpression)propertyExpression.Body).Member as PropertyInfo;
PropertyComparer<T> propertyComparer = new PropertyComparer<T>(propertyInfo);
actual.SequenceEqual(expected, propertyComparer).ShouldBeTrue();
}
}
public class PropertyComparer<T> : IEqualityComparer<T> {
private readonly PropertyInfo _propertyInfo;
public PropertyComparer(PropertyInfo propertyInfo) {
_propertyInfo = propertyInfo;
}
public bool Equals(T x, T y) {
object first = _propertyInfo.GetValue(x, null);
object second = _propertyInfo.GetValue(y, null);
if (first == null)
return second == null;
return first.Equals(second);
}
public int GetHashCode(T obj) {
object propertyValue = _propertyInfo.GetValue(obj, null);
if (propertyValue == null)
return 0;
else
return propertyValue.GetHashCode();
}
}
public class Point {
public decimal X { get; set; }
public decimal Y { get; set; }
public decimal Z { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment