【问题标题】:SQL to Linq converting using where in contains使用 where in contains 将 SQL 转换为 Linq
【发布时间】:2024-05-23 06:25:02
【问题描述】:

我已经写了这个 SQL 语句:

select id,ProductAbbr 
from Product  
where id in (Select max(id) from Product group by ProductAbbr)

我的 linq 查询是:

 var prod = (from t in _context.Product
             group t by t.ProductAbbr
             into g
             select new
                    {
                        Id = (from t2 in g select t2.Id).Max()
                    }).ToList();

// int idlist = Int32.Parse(prod);
var request = (from p in _context.Product
               where(p => prod.Contains(p.Id))
               select new
                      {
                          p.Id, p.ProductAbbr
                      }).ToList().Distinct();

我收到此错误

CS0136 C# 无法在此范围内声明名为“p”的本地或参数,因为该名称在封闭的本地范围中用于定义本地或参数

【问题讨论】:

    标签: sql asp.net-mvc linq


    【解决方案1】:

    不就是这样吗

    var prod = (from t in _context.Product
                group t by t.ProductAbbr
                           into g
                select new
                {
                    Id = (from t2 in g select t2.Id).Max()
                }).ToList();
    //int idlist = Int32.Parse(prod);
    var request = (from p in _context.Product
                   join p1 in prod on p1.Id equals p.Id
                   select new
                   {
                       p.Id,
                       p.ProductAbbr
                   }).ToList().Distinct();
    

    ?

    注意我已经改了

    where(p=> prod.Contains(p.Id))

    在 p1.Id 上加入 p1 等于 p.Id

    请注意,这将使您的查询在语法上有效,但似乎也可以根据我所看到的以许多其他方式对其进行修改。 至少在您的示例中,第二个查询似乎没有带来任何有用的信息。

    【讨论】: