C# linq:使用查询语法在何处插入 groupby

C# linq : using query syntax where to insert groupby

我试过不知道在哪里插入组

var filteredResult1 = from s in employeelist
                      group s by s.Department into s
                      where s.totalscore > 0 && s.totalscore <  400
                      select s.employeeID;

使用这段代码我得到了错误:

Error 2 'System.Linq.IGrouping' does not contain a definition for 'totalscore' and no extension method 'totalscore' accepting a first argument of type 'System.Linq.IGrouping' could be found (are you missing a using directive or an assembly reference?)

我的问题是,如何将 select employeeID where totalscore > 0 && totalscore < 400 group by department from employeelist 翻译成 Linq 语句。

你必须把你的 Linq 是这样的命令:

  1. 来自
  2. 在哪里
  3. 分组
  4. Select

在您的情况下,您可以这样做:

var filteredResult1 = employeelist.Where(emp => emp.totalscore > 0 && emp.totalscore < 400)
    .GroupBy(emp => emp.Department)
    .Select(grp => grp.Select(emp => emp.employeeID).ToList()).ToList();

使用查询语法:

var filteredResult2 = from emp in employeelist
                      where emp.totalscore > 0 && emp.totalscore < 400
                      group emp by emp.Department into grp
                      from emp in grp
                      select emp.employeeID;

emp代表一个Employee对象
grp 表示一个组(一个键和一个 Employee 对象列表)