无法将lambda表达式转换为' bool'因为它不是委托类型

时间:2015-10-04 18:31:54

标签: c# linq lambda

以下内容会返回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; }

2 个答案:

答案 0 :(得分:2)

您可以使用空条件访问(在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?之间没有隐式转换

答案 1 :(得分:0)

像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会提供将查询转换为方法链的选项(锤子图标)。