LINQ - sub-query in linq - Asked By Vaishu Vyas on 14-Apr-12 01:22 AM

how to use the SubQuery in LINQ???

Suchit shah replied to Vaishu Vyas on 14-Apr-12 01:26 AM
To use the sub-Query in LINQ you have to do your LINQ query like below example one

var query = from a in db.ONExport
  let ExportType = (from b in db.ONExportFlag
        where b.nOnFlagID == 13
        select b.sFlagValue).SingleOrDefault()
  let MultipleFileOutput = (from c in db.ONExportFlag
        where b.nOnFlagID == 21
        select b.sFlagValue).SingleOrDefault()
  select new
  {
    a.nONExportID,
    a.nExportDescription,
    a.sOutputFileName,
    ExportType,
    MultipleFileOutput
  };


Chintan Vaghela replied to Vaishu Vyas on 14-Apr-12 01:35 AM

Hello,

 

LINQ QUery

from p in db.Purchases

where p.Customer.Address.State == "WA" || p.Customer == null

where p.PurchaseItems.Sum (pi => pi.SaleAmount) > 1000

select p

Compare this to the SQL equivalent:

SELECT p.*

FROM Purchase p

    LEFT OUTER JOIN

      Customer c INNER JOIN Address a ON c.AddressID = a.ID

    ON p.CustomerID = c.ID  

WHERE

   (a.State = 'WA' || p.CustomerID IS NULL)

    AND p.ID in

    (

      SELECT PurchaseID FROM PurchaseItem

      GROUP BY PurchaseID HAVING SUM (SaleAmount) > 1000

    )

 

 

 

Hope this helpful!

Thanks

 

Vaishu Vyas replied to Vaishu Vyas on 14-Apr-12 01:39 AM
Thanks it works
Vaishu Vyas replied to Suchit shah on 14-Apr-12 01:43 AM
Thanks it works
Suchit shah replied to Vaishu Vyas on 14-Apr-12 01:44 AM
YOU ARE WELCOME 
kalpana aparnathi replied to Vaishu Vyas on 14-Apr-12 02:15 PM
hi,

There is no 'In' subquery in LINQ.Use the 'Any' operator to accomplish the same thing.The left-hand-side of the .Any() operator is the subquery.

              query.Any(x => predicate)

is equivalent to the SQL

              EXISTS(SELECT * FROM query WHERE predicate )

Regards,

Somesh Yadav replied to Vaishu Vyas on 16-Apr-12 01:16 AM
Hi,
 
Here I'm providing link for your requirement check this once
 
http://stackoverflow.com/questions/51339/how-can-you-handle-an-in-sub-query-with-linq-to-sql
 
All the Best