我有一个场景,我的数据看起来像这样。
Books --------------------------------- title | returnedDate Great Gatsby | 2015-05-04 Great Gatsby | 2015-03-22 Great Gatsby | 2015-01-11 Life of PI | 2015-04-04 Life of PI | 2015-04-02 Clean Code | 2015-06-05
I would like to return the most first and last book in each group (grouped by title) in a single linq statement. I know I can get the first or last item with a linq query like this.
var books = dbContext.Books
.GroupBy(b => b.title)
.Select(g => g.OrderDescending().FirstOrDefault());
如果最后一项也存在,我如何获得最后一项?
我的最终结果如下:
图书
---------------------------------
标题 |返回日期
了不起的 Gatsby | 2015-05-04
了不起的 Gatsby | 2015-01-11
PI的生活| 2015-04-04
PI的生活| 2015-04-02
清洁代码 | 2015-06-05
最佳答案
var books = dbContext.Books
.GroupBy(b => b.title)
.Select(g=>new {
Title=g.Key,
First=g.OrderByDescending(x=>x).FirstOrDefault(),
Last=g.OrderBy(x=>x).FirstOrDefault()
});
Results:
title | First | Last
Great Gatsby | 2015-05-04 | 2015-01-11
Life of PI | 2015-04-04 | 2015-04-02
Clean Code | 2015-06-05 | 2015-06-05
如果你真的像你问的那样想要它,那么它会变得有点困难:
var books = dbContext.Books
.GroupBy(b => b.title)
.Select(g=>new {
title=g.Key,
returnedDate=g.OrderByDescending(x=>x).FirstOrDefault()
}).Concat(
dbContext.Books
.GroupBy(b => b.title)
.Where(g=>g.Count()>1)
.Select(g=>new {
title=g.Key,
returnedDate=g.OrderBy(x=>x).FirstOrDefault()
})
).OrderBy(c=>c.title).ThenDescendingBy(c=>c.returnedDate);
哎呀。可能是更好的方法,但首先想到的是。
关于linq - 如果存在于组中,则获取第一项和最后一项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31549904/