I'm trying to order by the average score without dividing by zero:
var articles = (from f in DB.faqs
orderby f.scoreCount / f.scoreSum descending
select new Article(f.ID, f.question, f.scoreSum, f.scoreCount))
.Take(wantedItems);
Is there any way to achieve this in LINQ?
I suppose you want zero-score articles to be in the end:
orderby f.scoreSum == 0 ? 0 : f.scoreCount / f.scoreSum descending
Does this work?
orderby (f.scoreSum != 0) ? f.scoreCount / f.scoreSum : 0.0 descending
Not specific to linq:
f.scoreSum == 0 ? (f.scoreCount < 0 ? int.MinValue : int.MaxValue) : f.scoreCount / f.scoreSum
If not zero, it will do the regular division. If zero, it will take the closest integer to the right infinity (the one you would have gotten if you were using floats) so int.MinValue for where the result would have been negative infinity and int.MaxValue where the result would have been positive infinity.
Caveat: 0/0 also results in "as close to positive infinity as possible", if that's not ok you can add yet an other nested ternary .. or just filter the 0/0 cases out because 0/0 isn't really sortable anywhere anyway.
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