Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

LINQ to return only header items where line items are not zero

I have a simple sales header / sales line item table and I would like to return all header items where there the total quantity of line items is not zero

I thought I could just do a join but that returns the header items duplicated for each line item:

    var orders = from so in _ctx.SalesOrders
                 join soi in _ctx.SalesOrderItems on so.SalesOrderID equals soi.SalesOrderID
                 where so.IsDeleted != true
                 && so.IsCompleted != true
                 && soi.IsDeleted != true
                 && soi.QtyOutstanding > 0
                 select so;

How do I write my linq so that I only get a list of header items where the qty outstanding is above zero for any line item?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could wrap the Linq query syntax with a Dinstict() call:

(from so in _ctx.SalesOrders
join soi in _ctx.SalesOrderItems on so.SalesOrderID equals soi.SalesOrderID
where so.IsDeleted != true
&& so.IsCompleted != true
&& soi.IsDeleted != true
&& soi.QtyOutstanding > 0
select so).Distinct();

Alternatively, if you have navigation properties set up, you could use the regular Linq syntax without the need for a join or a Distinct():

var result = _ctx.SalesOrders
    .Where(so => 
        !so.IsDeleted && 
        !so.IsCompleted && 
        so.SalesOrderItems.Any(soi => !soi.IsDeleted && soi.QtyOutstanding > 0);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading