I want to do something like this:
public override int CompareTo (Foo rhs)
{
return Bar.CompareTo(rhs.Bar) ??
Baz.CompareTo(rhs.Baz) ??
Fuz.CompareTo(rhs.Fuz) ?? 0;
}
This doesn't work as written; is there some minimal workaround to make it work? Basically I want 0 to chain until non-zero (or end of chain).
Not supported by the language. But you can write a small helper like this:
public override int CompareTo (Foo rhs)
{
return FirstNonZeroValue(
() => Bar.CompareTo(rhs.Bar),
() => Baz.CompareTo(rhs.Baz),
() => Fuz.CompareTo(rhs.Fuz));
}
private int FirstNonZeroValue(params Func<int>[] comparisons)
{
return comparisons.Select(x => x()).FirstOrDefault(x => x != 0);
}
No basically, but it would be nice if it did (IIRC, Jon mentioned a similar idea in C# in Depth). You could probably chain conditionals, but I tend to just use:
int delta = Bar.CompareTo(rhs.Bar);
if(delta == 0) delta = Baz.CompareTo(rhs.Baz);
if(delta == 0) delta = Fuz.CompareTo(rhs.Fuz);
return delta;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With