There is a sheet

List.Add( new {tovar_code:1, tovar_kol:10, tovar_obyem:20} ) List.Add( new {tovar_code:2, tovar_kol:20, tovar_obyem:30} ) List.Add( new {tovar_code:3, tovar_kol:30, tovar_obyem:60} ) List.Add( new {tovar_code:4, tovar_kol:40, tovar_obyem:80} ) List.Add( new {tovar_code:5, tovar_kol:50, tovar_obyem:90} ) 

How to get the total amount of goods and their volumes in one linq query (total number 150, total volume 280)?

    2 answers 2

    Do you want total quantity and total volume? Then the easiest is just

     var total_quantity = List.Sum(x => x.tovar_kol); var total_volume = List.Sum(x => x.tovar_obyem); 

    If you want and really in one request, try this:

     var result = List.Aggregate( new { total_quantity = 0, total_volume = 0 }, (sum, curr) => new { total_quantity = sum.total_quantity + curr.tovar_kol, total_volume = sum.total_volume + curr.tovar_obyem }); 

    (but I don’t think it looks better, plus it allocates one temporary object per iteration).

    Well, in the end, do not forget about the good old foreach cycle:

     int total_quantity_2 = 0; double total_volume_2 = 0; foreach (var item in List) { total_quantity_2 += item.tovar_kol; total_volume_2 += item.tovar_obyem; } 

    Check: http://ideone.com/opDSgz

      Group by total for all records, not depending on the elements of the list, the key. For example, by the figure of 1. And we calculate the amount:

        var res=List.GroupBy(x=>1) .Select(x=>new { sum_kol=x.Sum(s=>s.tovar_kol), sum_obyem=x.Sum(s=>s.tovar_obyem) }) .DefaultIfEmpty(new {sum_kol=0, sum_obyem=0}) .First();