linq 无法将lambda表达式转换为类型“bool”,因为它不是委托类型

uqzxnwby  于 2022-12-15  发布在  其他
关注(0)|答案(3)|浏览(242)

下面的函数返回Cannot convert lambda expression to type 'bool' because it is not a delegate type

var Products = from s in db.Products where 
          ( from c in s.Manufacturers
  where (x => (from man in model.man where man.HasValue select man.Value).Contains(c.ManufacturerID)
  select c).Any()
  select s;

虽然这只是工作

if (model.man != null)
   {
        var students = from s in db.Products
                       where (from c in s.Manufacturers
                       where model.man.Contains(c.ManufacturerID)
                       select c).Any()
                       select s;
   }

在第一种情况下,我做错了什么?model.man声明为

public int?[] man { get; set; }
jbose2ul

jbose2ul1#

您可以使用null条件访问(在C# 6中)

var students = from s in db.Products
               where (from c in s.Manufacturers
               where model.man?.Contains(c.ManufacturerID) ?? false
               select c).Any()
               select s;

编辑:添加了?? false,因为boolbool?之间没有隐式转换

v8wbuo2f

v8wbuo2f2#

就像Rahul说的,你不能混合查询和方法的语法。

var Products = from s in db.Products
                       where(from c in s.Manufacturers
                             where (from man in model.man
                                    where man.HasValue
                                    select man.Value)
                                    .Contains(c.ManufacturerID)
                             select c).Any()
                       select s;

如果你想在特定的点使用lambda表达式,你总是可以用一个句点链接它,例如:

var Products = from s in db.Products
                           where(s.Manufacturers
                           .Where(c => (from man in model.man
                               where man.HasValue
                               select man.Value)
                               .Contains(c.ManufacturerID))).Any()
                           select s;

尽管出于个人喜好(可读性),我不希望混合这两种语法,如果你不熟悉方法语法,ReSharper确实提供了将查询转换为方法链的选项(锤子图标)。

6jygbczu

6jygbczu3#

我在一个简单的for循环中也遇到了同样的错误。错误是由于放错了“=”符号。
它是

for(int i=10;i=>0;i--)
{
 //your code
}

如果你仔细看代码,你会发现=被放在〉前面,它应该是小于或等于,即〉=
正确的代码应为

for(int i=10;i>=0;i--)
    {
     //your code
    }

希望这能帮到什么人。

相关问题