我在linq遇到小组问题。你可以在下面看到我的代码。
关注:我需要显示status=completed
和deleted=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>
结果。
请帮助我如何实现这个目标?
答案 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。