小编典典

如何将SQL“ HERE expr IN(查询)”转换为LINQ?

sql

基本上,我想使用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的正确语法是什么?


阅读 207

收藏
2021-04-22

共1个答案

小编典典

我有点晚了,但是我做了一个演示!

正如其他人所说,我始终使用Contains:

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; }
    }   
}
2021-04-22