Home > front end >  Linq vs foreach C#
Linq vs foreach C#

Time:06-07

I would like to write linq query for below code. I have a function which calculate the amount. How can I convert the code into linq for better performance and less line of code.

  public static class Product
    {
      int Id {get;set;}
      int amount {get;set;}
      string productName {get;set;}
    }
    
    public static class ProductContainer
    {
      public static IEnumerable<Product> ProductItems { get; set; }
    }
    
    Public class Calculation()
    {
    
     private int CalculateflybuysReturn()
        {
            // Adding product amount 
            // HOW CAN I CONVERT INTO LINQ and less line of code
               int amount =0
               foreach (var p in ProductContainer.ProductItems)
                {
                    if(p.Name == 'laptop')
                     amount  = int.Parse(P.amount, NumberFormatInfo.CurrentInfo);
                }    
        }
    }

CodePudding user response:

private int CalculateflybuysReturn()
{
    return ProductContainer.ProductItems.Where(p => p.Name == "laptop").Sum(p => int.Parse(p.Amount.ToString(), NumberFormatInfo.CurrentInfo));
}

CodePudding user response:

Something like this?

int amount = ProductContainer.ProductItems
    .Where(p => p.Name == "laptop")
    .Select(p => p.amount)
    .Sum();

CodePudding user response:

Could written as Simple as :

private int CalculateFlyBuysReturn(string NameString)
{
  return ProductContainer.ProductItems.Where(prd => prd.Name == NameString).Sum(prd => prd.Amount);
}

And Usage:

var SummedLaptopAmounts = CalculateFlyBuysReturn("Laptop");// if you want to get sum of filtered <Laptop> named items

Hope this helps.

  • Related