基本上我想用linq来创建这个SQL查询:
SELECT *
FROM Orders
WHERE Identifier IN (SELECT DISTINCT [Order] FROM OrderRows WHERE Quantity = '1')
这就是我的想法:
var q = from o in db.Orders
where o.Identifier in (from r in db.OrderRows
where r.Quantity == 1 select r.Order).Distinct());
但 o.Identifier 后的 无效。
关键字IN的正确语法是什么?
答案 0 :(得分:1)
from o in db.Orders
where o.Identifier.Any
(
from r in db.OrderRows
where r.Quantity == 1
select r.Order
).Distinct()
select o
试试这个......
答案 1 :(得分:1)
好像你想加入:
var q = (from o in db.Orders
join r in db.OrderRows on o.Identifier equals r.Order
where r.Quantity == 1
select o).Distinct();
答案 2 :(得分:1)
我有点晚了,但我做了一个演示!
正如其他人所说,我总是使用包含:
using System;
using System.Collections.Generic;
using System.Linq;
namespace ContainsExample
{
class Program
{
static void Main(string[] args)
{
var foos = new List<Foo>
{
new Foo { ID = 1, FooName = "Light Side" },
new Foo { ID = 2, FooName = "Dark Side" }
};
var bars = new List<Bar>
{
new Bar { ID = 1, BarName = "Luke", FooID = 1 },
new Bar { ID = 2, BarName = "Han", FooID = 1 },
new Bar { ID = 3, BarName = "Obi-Wan", FooID = 1 },
new Bar { ID = 4, BarName = "Vader", FooID = 2 },
new Bar { ID = 5, BarName = "Palpatine", FooID = 2 },
new Bar { ID = 6, BarName = "Fett", FooID = 2 },
new Bar { ID = 7, BarName = "JarJar", FooID = 3 }
};
var criteria = from f in foos
select f.ID;
var query = from b in bars
where criteria.Contains(b.FooID)
select b;
foreach (Bar b in query)
{
Console.WriteLine(b.BarName);
}
Console.WriteLine();
Console.WriteLine("There should be no JarJar...");
Console.ReadLine();
}
}
public class Foo
{
public int ID { get; set; }
public string FooName { get; set; }
}
public class Bar
{
public int ID { get; set; }
public string BarName { get; set; }
public int FooID { get; set; }
}
}
答案 3 :(得分:0)
int[] inKeyword = { 5, 7, 9 };
var q = from o in db.Orders.Where(p => inKeyword.Contains(p.Identifier));
希望有所帮助:)
答案 4 :(得分:0)
var q = from o in db.Orders
where (from r in db.OrderRows
where r.Quantity == 1 select r.Order).Distinct().Contains(o.Identifier);
答案 5 :(得分:0)
简短的回答是你想利用Contains
方法。
int[] ids = { 2, 5, 6, 1 };
var a = from myRecords in context.db
where ids.Contains (myRecords.id)
select new {Id = myRecords.id};
对两组结果进行过滤的方式相同,因为您可以过滤这两组共享的任何公共属性:
string[] cities = { "London", "Paris", "Seattle" };
var query = dataContext.Customers.Where (c => cities.Contains (c.City));