Avoid division by zero in the LINQ sequence

I'm trying to order a GPA 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?

+4
source share
7 answers

I suppose you want to have zero articles in the end:

 orderby f.scoreSum == 0 ? 0 : f.scoreCount / f.scoreSum descending 
+3
source

It works?

 orderby (f.scoreSum != 0) ? f.scoreCount / f.scoreSum : 0.0 descending 
+3
source

Not defined for linq:

 f.scoreSum == 0 ? (f.scoreCount < 0 ? int.MinValue : int.MaxValue) : f.scoreCount / f.scoreSum 

If not zero, it will perform regular division. If it is zero, it will take the closest integer to right infinity (the one you would get if you used float), so that int.MinValue, where the result would be negative infinity and int.MaxValue, where the result would be positive infinity.

Caveat: 0/0 also leads to being โ€œas close to positive infinity as possible,โ€ if that's not normal, you can add another nested ternary .. or just filter out 0/0 cases, because 0/0 isnโ€™t really sorted anyway.

+1
source

Try just checking the value 0 before dividing.

 var articles = (from f in DB.faqs orderby f.scoreSum == 0 ? 0 : f.scoreCount / f.scoreSum descending select new Article(f.ID, f.question, f.scoreSum, f.scoreCount)) .Take(wantedItems); 
0
source
 var articles = (from f in DB.faqs orderby f.scoreSum!=0? (f.scoreCount / f.scoreSum) : 0 descending select new Article(f.ID, f.question, f.scoreSum, f.scoreCount)) .Take(wantedItems); 
0
source
 f.scoreSum != 0 ? f.scoreSum : 1 
0
source

Assuming you donโ€™t need records where scoreSum is 0 (invalid records?) And not perform all the calculations in the Orderby clause, try adding a filter to the where clause, as this should reduce the tables and improve performance.

 var articles = (from f in DB.faqs where f.scoreSum != 0 orderby f.scoreCount / f.scoreSum descending select new Article(f.ID, f.question, f.scoreSum, f.scoreCount)) .Take(wantedItems); 
0
source

All Articles