none
C# - how to use LINQ to do some basic math RRS feed

  • Question

  • Hello:

    I have the following code:

            public struct Amount
            {
                public double volume { get; set; }
                public double price { get; set; }
            }
    
            public struct AvergeItem
            {
                public double total_amount { get; set; }
                public double weighted_price { get; set; }
            }
    
            static void Main(string[] args)
            {
                List<Amount> total_items = new List<Amount>();
                Amount item1 = new Amount { volume = 1.0, price = 1.0 };
                Amount item2 = new Amount { volume = 2.0, price = 2.0 };
                Amount item3 = new Amount { volume = 3.0, price = 3.0 };
                total_items.Add(item1);
                total_items.Add(item2);
                total_items.Add(item3);
    
                Amount avg_item = new AvergeItem { total_amount = 14.0, weighted_price = 1.0 };
    }
    
    

    Here is the equation to calculate the average item:

    Grand total = sum of (volume * price)
    Grand total = (1 * 1) + (2 * 2) + (3 * 3) = 1 + 4 + 9 = 14
    This grand total is the total_amount in AverageItem.
    Weighted price = (1*1)/14 + (2*2)/14 + (3*3)/14 = 1

    I know how to do this without LINQ, but I want to know how to do this with LINQ.

    Thanks,

    Thursday, June 21, 2018 2:15 PM

Answers

  • The solution to this is trivial. You can use the Sum method to get this done like:

    var grandTotal = total_items.Sum(x=> x.price * x.volume);
    Console.WriteLine(grandTotal);
    		
    var weightedAmount = total_items.Sum(x=> (x.price * x.volume)/grandTotal);
    Console.WriteLine(weightedAmount);


    See the following working demo fiddle for this :

    https://dotnetfiddle.net/TPZr8k

    Hope it helps!


    [If a post helps to resolve your issue, please click the "Mark as Answer" of that post or click Answered"Vote as helpful" button of that post. By marking a post as Answered or Helpful, you help others find the answer faster. ]


    Blog | LinkedIn | Stack Overflow | Facebook
    profile for Ehsan Sajjad on Stack Exchange, a network of free, community-driven Q&A sites


    • Edited by Ehsan Sajjad Thursday, June 21, 2018 2:33 PM
    • Marked as answer by zydjohn Thursday, June 21, 2018 5:03 PM
    Thursday, June 21, 2018 2:30 PM