Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq How to Get Average When all values equals null or 0 ? MVC

When my model has values, i can get the average easily with this code

@Model.Where(a => a.count!= null).Average(a => a.totalday).ToString()

For example:

count = 7 totalday= 3 average= 2.33

But i can't get average value when my model values equals to null or zero. As you know we can't divide 0 to 0 or null to null.

I mean;

count = 0 or null; totalday= 0 or null; average= ????

If all values are null, how can i write my table to "0" or a string like "there is no any average"

I tried lots of things but i get an error.

like image 446
kojirosan Avatar asked Sep 10 '14 11:09

kojirosan


1 Answers

It really depends on what you want do do. If you're ok with having some sort of default value for the average then you can use DefaultIfEmpty

@Model.Where(a => a.count!= null)
      .Select(a => a.totalday)
      .DefaultIfEmpty(0)
      .Average()
      .ToString()

But if it would be better to display something else entirely then you'll have to first check whether there are any elements in the filtered sequence.

like image 55
Dirk Avatar answered Sep 27 '22 19:09

Dirk