gpt4 book ai didi

c# - 如何将 SQL "WHERE expr IN (query)"翻译成 LINQ?

转载 作者:行者123 更新时间:2023-11-30 12:16:52 24 4
gpt4 key购买 nike

基本上我想用 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 是无效的。

关键字 IN 的正确语法是什么?

最佳答案

有点晚了,不过我做了一个demo!

正如其他人所说,我总是使用包含:

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; }
}
}

关于c# - 如何将 SQL "WHERE expr IN (query)"翻译成 LINQ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4513454/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com