User987
User987

Reputation: 3823

Divding property by property in LINQ expression

I have written a code like below:

Session["priceRange"] = ranges.Select(r => new PriceRangeGraph
{
     Price = Math.Round(r, 2),
     Sales = lista.Where(x => ranges.FirstOrDefault(y => y >= x.SalePrice) == r).Sum(x => x.SaleNumber),
     SuccessfulSellers = lista.GroupBy(x => x.StoreName).Where(x => ranges.FirstOrDefault(y => y >= x.Select(z => z.SalePrice).FirstOrDefault()) == r && x.Select(h => h.SaleNumber).FirstOrDefault() > 0).Count(),
     UnSuccessfulSellers = lista.GroupBy(x => x.StoreName).Where(x => ranges.FirstOrDefault(y => y >= x.Select(z => z.SalePrice).FirstOrDefault()) == r && x.Select(h => h.SaleNumber).FirstOrDefault() == 0).Count(),
}).ToList();

What this does is following:

Now I'd like to get successful sell through rate for sellers that had sales and for those haven't. The way i'd do this is:

(thoseWhoHadSales/(thoseWhoHadSales+thoseWhoDidnt))*100;

Where I would get the success sell-through for the sellers within that given price range.

Now what I'm confused about are exceptions that do/might occur:

Divide by zero exception... If those who had sales is equal to = 0;

And what is the easiest way for me to now to perform the formula that I've shown above. Can I do it right away within the select statement somehow ?

And if those who had sales for the given price range is = 0, I would simply set the sell through to 0...

Can someone help me out?

Stephen, you mean something like this:

public double SellThroughRate
{
    get { return SellThroughRate; }
    set
    {
        if (SuccessfulSellers != 0)
        {
            SellThroughRate = Math.Round((SuccessfulSellers / (SuccessfulSellers + UnSuccessfulSellers)) * 100,2);
        }
        else
        {
            SellThroughRate = 0;
        }
    }
}

Upvotes: 0

Views: 85

Answers (2)

Berkay Yaylacı
Berkay Yaylacı

Reputation: 4513

double.IsNaN() can be an alternative for checking equals to zero condition,

double tempResult = Math.Round(((double)SuccessfulSellers / ((double)SuccessfulSellers + (double)UnSuccessfulSellers)) * 100,2);
SellThroughRate = double.IsNaN(tempResult) ? 0 : tempResult;

Hope helps,

Upvotes: 1

user3559349
user3559349

Reputation:

Make your property readonly, and conditionally check if SuccessfulSellers + UnSuccessfulSellers is zero to prevent the exception. I also recommend you store the result as is, and use a [DisplayFormat] attribute for displaying the formatted result in the view

[DisplayFormat(DataFormatString = "{0:P2}")]
public double SellThroughRate
{
    get
    {
        double total = SuccessfulSellers + UnSuccessfulSeller;
        return total  == 0 ? 0 : SuccessfulSellers / total;
    }
};

Upvotes: 1

Related Questions