开发者

Get objects with max value from grouped by linq query

开发者 https://www.devze.com 2023-02-14 12:42 出处:网络
I got the following linq query: var invadersOrderedInColumns = from i in invaders group i by i.GetPosition().X;

I got the following linq query:

var invadersOrderedInColumns = from i in invaders
                               group i by i.GetPosition().X;

This will order the invaders with the same X position. The next thing I want to do is retrieve the invader with the highest Y value from each of those columns.

Imagine if you will each invader as a black blok in the following image. This w开发者_StackOverflow社区ill represent the invaders after the above linq query. Each X = Value is the key.

Get objects with max value from grouped by linq query

Now, from each of these groups (columns), I want to get the invaders with the highest Y position (so the bottom invader of each column when you look at the picture):

Get objects with max value from grouped by linq query

How can I get this done with a Linq query?


I don't much care for the query syntax, but in extension method syntax it would look something like this.

var invadersOrderedInColumns = invaders
    .GroupBy(d => d.GetPosition().X)
    .Select(d => d.OrderByDescending(y => y.GetPosition().Y).First());
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号