如何编写以下场景的查询?

时间:2014-05-26 06:04:38

标签: c# .net linq linq-to-sql

我在linq遇到小组问题。你可以在下面看到我的代码。

关注:我需要显示status=completeddeleted=false,然后会得到IEnumerable以下结果。

示例数据:

Id appName        role    Type    Status      createdAt
1  application1  role1   false    completed   25/05/2014 12.00.00
2  application1  role1   true     completed   25/05/2014 11.00.00
3  application1  role1   true     completed   25/05/2014 11.00.00
4  application2  role1   true     completed   25/05/2014 11.00.00
5  application2  role1   false    completed   25/05/2014 10.00.00

在上面的IEnumerable结果中,我需要像

这样的输出

预期输出:

Id appName        role    Type    Status      createdAt
4  application2  role1   true     completed   25/05/2014 11.00.00

我在Linq查询中尝试了这个:

代码:

var arr = from m in m_Repo.All().AsEnumerable()
          .Where(a => a.Status == Completed && a.ID== 12 && a.IsDeleted == false)
          group m by new { m.Name } into g
          select g.OrderByDescending(gg => gg.UpdatedAt).Take(1)
          .Where(dd => dd.Type == true);

但不给出输出。我收到IEnumerable<IEnumerable>结果。

请帮助我如何实现这个目标?

2 个答案:

答案 0 :(得分:0)

var arr = from m in m_Repo.All().AsEnumerable()
          .Where(a => a.Status == Completed && a.ID== 12 && a.IsDeleted == false)
          group m by new { m.Name } into g
          select g.OrderByDescending(gg => gg.UpdatedAt).Take(1)
          .Where(dd => dd.Type == true).First();

答案 1 :(得分:0)

var arr = m_Repo.All().AsEnumerable()
                .Where(a => a.Status == Completed && a.ID== 12 && !a.IsDeleted)
                //No need to group by new if you have only one property to group by
                .GroupBy(m => m.Name)
                .Select(g => g.OrderByDescending(x => x.UpdateAt))
                //this will give the first group (by name), with highest UpdateAt
                .First()
                //this will return the first element of this group with Type true
                .FirstOrDefault(dd => dd.Type);

var arr = m_Repo.All().AsEnumerable()
                .Where(a => a.Status == Completed && a.ID== 12 && !a.IsDeleted)
                .GroupBy(m => m.Name)
                .OrderByDescending(g => g.Select(x => x.UpdateAt))
                .First()
                .FirstOrDefault(a => a.Type);

您可能需要OrderByDescending(x => x.Id)First()FirstOrDefault()之间,如果您想要最大的ID。