c# - Chaining to clean up CompareTo -
every time need write compareto
method in c#, hate fact can't chain tests , results in javascript:
function int compareto(a, b) { return a.value1 - b.value1 || a.value2 - b.value2 || a.value3 - b.value3; }
instead in c# looks like:
int compareto(object obj) { var other = obj myclass; if (other == null) return 0; int result = value1 - other.value1; if (result != 0) return result; result = value2 - other.value2; if (result != 0) return result; return value3 - other.value3; }
is there way write above 'cleaner'? doesn't have one-liner in javascript, should more readable , less error-prone.
using generic extension method nullablecompareto
can make use of ?? operator
refactor compareto
method to:
int compareto(object obj) { var other = obj myclass; if (other == null) return 0; return value1.nullablecompareto(other.value1) ?? value2.nullablecompareto(other.value2) ?? value3.compareto(other.value3); }
extension method
public static class comparableextensions { /// <summary> /// same compareto returns null instead of 0 if both items equal. /// </summary> /// <typeparam name="t">icomparable type.</typeparam> /// <param name="this">this instance.</param> /// <param name="other">the other instance.</param> /// <returns>lexical relation between , other instance or null if both equal.</returns> public static int? nullablecompareto<t>(this t @this, t other) t : icomparable { var result = @this.compareto(other); return result != 0 ? result : (int?)null; } }
Comments
Post a Comment