Reputation: 4053
I'm 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 find "Orders that not have the same TOTRGVS
in OrderHeader
and OrderDetail
", so I tried 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 don't know how to retrieve the TOTRGVS
field from OrderHeader
. I have tried using Key but can't get any field, just extensions for formatting methods.
Upvotes: 1
Views: 4990
Reputation: 110071
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();
Upvotes: 2
Reputation: 117220
The Except
function is normally used to determine differences in lists.
Upvotes: 1