views:

842

answers:

2

Hello, Im stuck with a LINQ group by situation trying to solve it without using foreach statement, here is the escenary:

I Have two generic collections List<OrderHeader> and List<OrderDetail>, both have a same field "TOTRGVS" that contains total amount from a order, and the number of order is the key named "NDORGV".

Then I want to found "Orders that not have the same TOTRGVS in OrderHeader and OrderDetail". So for regarding this I try the following query:

   List<RGVCAFAC_ERRORES> diff = (from d in lstOrderDetail 
                               join c in lstOrderHeader on d.NDORGV equals c.NDORGV                                                     
                                      group d by d.NDORGV into g
                               let difTOTOrderDetail = g.Select(p => p.TOTRGVS).Sum()
                               let difTOTOrderHeader = g.Key.????
                               let diffTOT = difTOTOrderHeader - difTOTOrderDetail
                               where diffTOT != 0
                                      select new _ERRORS
                                      {

                                          NDORGV = g.Key,
                                          IMPORT = diffTOT
                                      }

  ).ToList();

in difTOTOrderHeader I dont know how to retrieve the TOTRGVS field from OrderHeader, I have trying using Key but cant get any field, just extensions for formatting methods.

Im in a good way or not?

Thanks.

+1  A: 

The Except function is normally used to determine differences in lists.

leppie
Excepts in Header or Detail? when already exists a group by X and X determines the "selected objects", also I forget tell that Detail can have more than one row thats the cause I use group sum!
Angel Escobedo
+1  A: 

This might do the trick:

var dictDetails = lstOrderDetail
  .GroupBy(d => d.NDORGV)
  .ToDictionary(g => g.Key, g => g.Sum(d => d.TOTRGVS));

var result = lstOrderHeader
  .Where(h => dictDetails[h.NDORGV] != h.TOTRGVS)
  .ToList();
David B