Reputation: 68750
(Linq)
I have a simple object let's call Dog in a simple List of Dog
Dog
Id (Unique)
GroupBarkId
Name
I need to get all the Dogs that have the same highest GroupBarkId
Id GroupdBarkId
1 2
2 2
3 2
4 3
5 3
6 3
So I'd need the list to have, in this case, the GroupBarkId equals to 3.
I don't know the highest GroupBarkId when I do the query
Upvotes: 0
Views: 53
Reputation: 101681
var dogs = db.Dogs.Where(d => d.GroupdBarkId == db.Dogs.Max(d => d.GroupdBarkId))
.ToList();
Or first get the maximum Id:
var id = db.Dogs.Max(d => d.GroupdBarkId);
var dogs = db.Dogs.Where(d => d.GroupdBarkId == id)
.ToList();
Upvotes: 2
Reputation: 460068
You can use Enumerable.GroupBy
+ OrderByDescending
:
List<Dog> dogsWithHighestGroupBarkId = dogs
.GroupBy(d => d.GroupBarkId)
.OrderByDescending(grp => grp.Key)
.First()
.ToList()
Upvotes: 2