Linq Query Calculation RRS feed

  • Question

  • I have below data inside my object 

    var summary =  new List<OrderSummary>();

    summary.Add(new OrderSummary(){Name = "John", Expected=10, Actual = 10});

    summary.Add(new OrderSummary(){Name = "John", Expected=20, Actual = 40});

    summary.Add(new OrderSummary(){Name = "Peter", Expected=3, Actual = 10});

    summary.Add(new OrderSummary(){Name = "Peter", Expected=10, Actual = 4});

    now i wanted to create a new object (CalculationSummary)  based on the above object values with below properties  on it with below values 

    Name , TotalExpected , TotalActual  

    I want to populate my new object  with group by Name and need to calculate total of expected and actual values 

    can we write a Linq Query to get this figures ? 


    Wednesday, May 20, 2020 4:11 PM


  • Yes you can use the GroupBy method or `group by` keywords.

    //Not tested...
    var results = from o in summary
                  group o by o.Name into g
                  select new { Name = g.Key, TotalExpected = g.Sum(x => x.Expected), TotalActual = g.Sum(x => x.Actual) };
    I'm using an anonymous type here. Replace with your actual type name.

    Michael Taylor

    • Marked as answer by kavithma Wednesday, May 20, 2020 7:50 PM
    Wednesday, May 20, 2020 4:49 PM