如何使用LINQ to SQL处理IN子查询?

时间:2008-09-09 07:20:51

标签: sql linq linq-to-sql

我有点坚持这个。基本上我想在LINQ to SQL中执行类似以下SQL查询的操作:

SELECT f.* 
FROM Foo f
WHERE f.FooId IN (
    SELECT fb.FooId
    FROM FooBar fb
    WHERE fb.BarId = 1000
)

感谢任何帮助。

感谢。

9 个答案:

答案 0 :(得分:82)

在LINQ to SQL中实现IN的一般方法

var q = from t1 in table1
        let t2s = from t2 in table2
                  where <Conditions for table2>
                  select t2.KeyField
        where t2s.Contains(t1.KeyField)
        select t1;

在LINQ to SQL中实现EXISTS的一般方法

var q = from t1 in table1
        let t2s = from t2 in table2
                  where <Conditions for table2>
                  select t2.KeyField
        where t2s.Any(t1.KeyField)
        select t1;

答案 1 :(得分:58)

看看this article。基本上,如果要获得等效的IN,则需要首先构造内部查询,然后使用Contains()方法。这是我翻译的尝试:

var innerQuery = from fb in FoorBar where fb.BarId = 1000 select fb.FooId;
var result = from f in Foo where innerQuery.Contains(f.FooId) select f;

答案 2 :(得分:3)

from f in Foo
    where f.FooID ==
        (
            FROM fb in FooBar
            WHERE fb.BarID == 1000
            select fb.FooID

        )
    select f;

答案 3 :(得分:2)

尝试使用两个单独的步骤:

// create a Dictionary / Set / Collection fids first
var fids = (from fb in FooBar
            where fb.BarID = 1000
            select new { fooID = fb.FooID, barID = fb.BarID })
            .ToDictionary(x => x.fooID, x => x.barID);

from f in Foo
where fids.HasKey(f.FooId)
select f

答案 4 :(得分:1)

//首先创建一个Dictionary / Set / Collection fids

Find Other Artilces

var fids = (from fb in FooBar
            where fb.BarID = 1000
            select new { fooID = fb.FooID, barID = fb.BarID })
            .ToDictionary(x => x.fooID, x => x.barID);

from f in Foo
where fids.HasKey(f.FooId)
select f

答案 5 :(得分:0)

试试这个

var fooids = from fb in foobar where fb.BarId=1000 select fb.fooID
var ff = from f in foo where f.FooID = fooids select f

答案 6 :(得分:0)

var foos = Foo.Where<br>
( f => FooBar.Where(fb.BarId == 1000).Select(fb => fb.FooId).Contains(f.FooId));

答案 7 :(得分:0)

//首先创建一个Dictionary / Set / Collection fids

Find Other Artilces

var fids = (from fb in FooBar where fb.BarID = 1000 select new { fooID = fb.FooID, barID = fb.BarID }) .ToDictionary(x => x.fooID, x => x.barID);

from f in Foo where fids.HasKey(f.FooId) select f

答案 8 :(得分:0)

from f in foo
where f.FooID equals model.FooBar.SingleOrDefault(fBar => fBar.barID = 1000).FooID
select new
{
f.Columns
};