查询主体必须使用lambda表达式在Linq查询中以select子句或group子句结束

时间:2017-09-22 19:54:13

标签: c# linq lambda

我在这里使用lambda表达式Linq查询并抛出错误

  

查询正文必须以select子句或group子句结尾

以下是有问题的查询

var query = from county in HWC.StateCounties.Where(w => w.StateID == id).Select(s => new CountyList
    {
        CountyID = s.StateCountyID,
        CountyName = s.CountyName
    });

我甚至尝试在最后添加.Tolist()并得到同样的错误。

为什么当我明确有一个select子句时会发生这种情况?

2 个答案:

答案 0 :(得分:1)

我在查询中犯了一个错误,查询应该是这个

  User.IsInRole("admin");

答案 1 :(得分:1)

虽然可以组合Linq和扩展方法,但Linq查询总是需要以c#中的select结尾(在vb中这不是必需的)。 也许这是一个品味问题,但我更喜欢Linq而不是扩展方法,因为它使代码更具可读性,因为所有大括号都被移除了。

您的查询将如下所示

var query = 
   from county in HWC.StateCounties
   where county.stateID == id
   select new
   {
       county.StateCountyID,
       county.CountyName,
   };

如果要组合查询,将显示如下:

var query = 
   from county in HWC.StateCounties.Where(s => s.stateID == id)
   select new
   {
       county.StateCountyID,
       county.CountyName,
   };