【问题标题】:Linq: Adding extra condition along with GroupBy and SelectManyLinq:与 GroupBy 和 SelectMany 一起添加额外的条件
【发布时间】:2018-06-15 22:17:31
【问题描述】:

继续我之前的帖子: SQL Query: Display only latest Id from each set

我有以下 SQL 表:

Name       Description   Id   UserId   CreatedDate

UserSet1   Desc1         0    Abc      06/01/2018
UserSet1   Desc2         1    Abc      06/01/2018
UserSet1   Desc4         2    Def      06/02/2018
UserSet2   Desc for 2    5    NewUser  06/04/2018
UserSet2   Desc for 2    7    NewUser  06/19/2018

我想从上表中提取的只是每个 Name 的最新 Id,以便我可以得到以下输出

Name      Description    Id    UserId    CreatedDate

UserSet1  Desc1          0     Def       06/01/2018
UserSet1  Desc2          2     Def       06/01/2018
UserSet2  Desc for 2     7     NewUser   06/19/2018

由于 Id 2 和 7 是表中 UserSet1 和 UserSet2 的最新条目,我想显示它而不是表中的所有条目。现在用下面的 LINQ 代码解决了这个问题。现在我有另一个要求,也显示所有 ID 为 0 的行(见上面的预期结果)。

var results = response
  .GroupBy(row => row.Name)
  .SelectMany(g => g
     .OrderByDescending(row => row.Id)
     .Take(1));

如何修改我上面的 Linq,以便它显示该名称的所有最高无 ID 以及任何为零的 ID。

谢谢

【问题讨论】:

    标签: c# linq


    【解决方案1】:
      var results = response.GroupBy(row => row.Name)
                            .SelectMany(g => g
                            .OrderByDescending(row => row.Id)
                            .Take(1))
                          .Union(response.Where(x=>x.Id== 0));
    

    【讨论】:

    • 谢谢,就是这样。我错过了联合声明。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-28
    • 1970-01-01
    • 1970-01-01
    • 2014-05-19
    • 2013-11-24
    相关资源
    最近更新 更多