Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid division by zero in LINQ orderby

Tags:

c#

linq

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?

like image 410
cptloop Avatar asked Oct 14 '11 09:10

cptloop


3 Answers

I suppose you want zero-score articles to be in the end:

orderby f.scoreSum == 0 ? 0 : f.scoreCount / f.scoreSum descending
like image 92
Jacek Gorgoń Avatar answered Sep 21 '22 04:09

Jacek Gorgoń


Does this work?

orderby (f.scoreSum != 0) ? f.scoreCount / f.scoreSum : 0.0 descending
like image 28
Will Avatar answered Sep 22 '22 04:09

Will


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.

like image 42
harold Avatar answered Sep 18 '22 04:09

harold