[英]Select all distinct last records of column1 and order by column2 in Linq (Not Working Accordingly)
So I have a table like this:所以我有一个这样的表:
Now I want distinct ShortCode
order by the ID
descending.现在我想要按
ID
降序排列的不同ShortCode
顺序。 In other words, the distinct last records.换句话说,不同的最后记录。 Like this:
像这样:
So I tried GroupBy like:所以我尝试了 GroupBy,比如:
var data = db.ShortCodes.GroupBy(x => x.ShortCode).Select(x => x.FirstOrDefault()).OrderByDescending(s=> s.ID);
This gave me distinct records but not the last ones, nor ordered by ID descending:这给了我不同的记录但不是最后的记录,也没有按 ID 降序排列:
Now I also tried like suggested here现在我也尝试了这里的建议
var data = db.ShortCodeManager
.GroupBy(s => s. ShortCode)
.Select(g => g.First())
.OrderByDescending(s => s.ID);
This gave me the error The method 'First' can only be used as a final query operation. Consider using the method 'FirstOrDefault' in this instance instead.
这给了我错误
The method 'First' can only be used as a final query operation. Consider using the method 'FirstOrDefault' in this instance instead.
The method 'First' can only be used as a final query operation. Consider using the method 'FirstOrDefault' in this instance instead.
So I modified to FirstOrDefault()
like:所以我修改为
FirstOrDefault()
像:
var data = db.ShortCodeManager
.GroupBy(s => s. ShortCode)
.Select(g => g.FirstOrDefault())
.OrderByDescending(s => s.ID);
This also gave me distinct records but not the last records:这也给了我不同的记录,但不是最后的记录:
So finally I tried like suggested here :所以最后我按照这里的建议尝试了:
var data = db.ShortCodeManager.Where(a => a.ID > 0).GroupBy(x => x.ShortCode).OrderByDescending(grp => grp.Max(g => g.ID)).Select(a => a.FirstOrDefault());
Again, this gave me distinct records but not the last ones, nor ordered by ID descending:同样,这给了我不同的记录,但不是最后一个,也没有按 ID 降序排列:
So how am I to write the query to get the result I want in Linq?那么我该如何编写查询以在 Linq 中获得我想要的结果呢? Also note, I need more of the distinct last records than ordering by
ID
descending.另请注意,与按
ID
降序排序相比,我需要更多不同的最后记录。 If anyone also knows how to write it in raw SQL it might be useful as well.如果有人也知道如何在原始 SQL 中编写它,它也可能有用。
This LINQ query should work for your case:此 LINQ 查询应该适用于您的情况:
var result = db.ShortCodeManager
.GroupBy(x => x.ShortCode)
.Select(gr => new { Id = gr.Max(g => g.Id), ShortCode = gr.Key})
.ToList();
EDIT:编辑:
Based on your comment it looks like you need to cast anonymous object result
to ShortCodeManagerModel
type and then pass it to your view.根据您的评论,您似乎需要将匿名 object
result
转换为ShortCodeManagerModel
类型,然后将其传递给您的视图。 So, somethin like this:所以,像这样:
var result = db.ShortCodeManager
.GroupBy(x => x.ShortCode)
.Select(gr => new { Id = gr.Max(g => g.Id), ShortCode = gr.Key})
.ToList();
var model = result
.Select(x => new ShortCodeManagerModel { Id = x.Id, ShortCode = x.ShortCode })
.ToList();
And then pass model
to you view.然后传
model
给你查看。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.