4

Currently I have a List of objects in which I need to find all occurrences that have the maximum value.

Currently my solution to this has been:

Foo maxFoo = list.OrderByDescending(foo => foo.A).First();
List<Foo> maxFoos = new List<Foo>();

foreach(Foo foo in list) {
    if (foo.A.Equals(maxFoo.A)) {
        maxFoos.Add(foo);
    }
}

However I want to know if there is a way to do this in a single Linq expression.

All the resources I have read only refer to getting the max value for one object.

Note: For the time being, I want to know a solution which doesn't rely on MoreLinq

3 Answers 3

3

You can group by the property, then order the groups by key, and take the content of the first one, like this:

var res = list
    .GroupBy(item => item.A)
    .OrderByDescending(g => g.Key)
    .First()
    .ToList();
Sign up to request clarification or add additional context in comments.

Comments

2

You could group by A, order the group, and get the elements in the first group, which corresponds to the elements with the max value of A:

list
  .GroupBy(x => x.A)
  .OrderByDescending(grp=> grp.Key)
  .First()
  .Select(x => x);

Comments

1

This works:

var maxFoos =
    list
        .OrderByDescending(foo => foo.A)
        .GroupBy(foo => foo.A)
        .Take(1)
        .SelectMany(foo => foo)
        .ToList();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.