[Solved] How to Calculate a Discount In LINQ [closed]


Firstly this code is really starting to need a ViewModel or some other construct that would enable you to decouple your business logic from your UI.

Having said that, the quick and dirty answer to get you going, would be to implement an interim linq query and then build your results from that

// From your code
var validRows = gridpur.Rows.Cast<GridViewRow>()
    .Where(r => ((CheckBox)r.FindControl("chkSel")).Checked);
var totals = validRows.Select((r => 
    double.Parse(((TextBox)r.FindControl("txtQuantity")).Text)
    * double.Parse(((TextBox)r.FindControl("txtUnitprice")).Text));

It will also help if we move from linq as extension methods to linq as integrated query syntax, but feel free to mix and match

var validRows = from r in gridpur.Rows.Cast<GridViewRow>()
    where ((CheckBox)r.FindControl("chkSel")).Checked)
    select r;
var totals = from r in validRows
   select double.Parse(((TextBox)r.FindControl("txtQuantity")).Text)
    * double.Parse(((TextBox)r.FindControl("txtUnitprice")).Text));

We can now introduce let statement and intermediary variables in the query

var totals = from r in validRows
   let quantity = double.Parse(((TextBox)r.FindControl("txtQuantity")).Text)
   let unitPrice = double.Parse(((TextBox)r.FindControl("txtUnitprice")).Text))
   select quantity * unitPrice;

This has a major benefit of making the query more readable.

Now we can add other columns and calculations

var totals = from r in validRows
   let quantity = double.Parse(((TextBox)r.FindControl("txtQuantity")).Text)
   let unitPrice = double.Parse(((TextBox)r.FindControl("txtUnitprice")).Text))
   let discountPercent = double.Parse(((TextBox)r.FindControl("txtDiscount")).Text) / 100.0d
   select quantity * unitPrice * discountPercent;
 var sumTotals = totals.Sum();

0

solved How to Calculate a Discount In LINQ [closed]