Correlated SubQuery SQL to LINQ

守給你的承諾、 提交于 2019-12-11 17:13:30

问题


select * 
  from Table1 
 where TC in (select TC 
                from Table2 
               where Application in ('AAA'))`

help me in converting above query to LINQ.


回答1:


Without where Application in ('AAA') part this looks quite simple:

from t1 in db.Table1s
where db.Table2s.Select(t2 => t2.TC).Contains(t1.TC)
from t1 in db.Table1s

UPDATE (How wrong I was!)

List<string> myCollection = new List<string> { "AAA" };
from t1 in db.Table1s
where db.Table2s.Where(t2 => myCollection.Contains(t2.Application)).Select(t2 => t2.TC).Contains(t1.TC)
from t1 in db.Table1s

should work with in-code collections.




回答2:


Try in this way

There is no 'In' subquery in LINQ (so far).

Use the 'Any' operator to accomplish the same thing.

For example:

all customers that are located in the same city as an employee

   from c in db.Customers
   where db.Employees.Any(e => e.City == c.City)
   select c;

or

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
    )

get more details here

http://social.msdn.microsoft.com/Forums/en-AU/linqprojectgeneral/thread/360166df-4e50-44d8-812a-04b5bc4fedd1



来源:https://stackoverflow.com/questions/6979389/correlated-subquery-sql-to-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!