Link to home
Start Free TrialLog in
Avatar of XTO
XTO

asked on

LINQ query to get element with highest score

I'm trying to get an object in a list of objects that has the highest score. If there are two or more objects with equal high scores, I can get the first, either, or any.
Is the code below the best way to do it, or is there a better way?

 List<AddressCandidate> returnedCandidates = args.Results;

// Get the AddressCandidate with the highest addressCandidate score.
AddressCandidate addCand =   (
                from address in returnedCandidates
                let high = returnedCandidates.Max(highest => highest.Score)
                where address.Score == high
                select address).First();

Open in new window

Avatar of Jens Fiederer
Jens Fiederer
Flag of United States of America image

I prefer using the order by clause....probably more efficient, too.
Avatar of XTO
XTO

ASKER

I should add this.
I'm thinking that the above can't be the most efficient way.

Here's why:

Suppose that returnedCandidates has a count of 8 objects.
As I step through the code in debug mode, the debugger goes through all 8 objects in step 4 above.
Then the debugger goes to step 5, and then returns back to step 4 for 8 more loops.
In other words, the debugger hits step 5 a total of 8 times, which means that step 4 gets looped 64 times total.
That seems slower than if I had just done a for loop and captured an object with the highest score.
ASKER CERTIFIED SOLUTION
Avatar of Jens Fiederer
Jens Fiederer
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
(or, actually, LAST)
Avatar of XTO

ASKER

re: jensfiederer,

I'm going to try to create an example using an order by clause and post it here.
Avatar of XTO

ASKER

Our posts crossed.
Avatar of XTO

ASKER

re: jensfiederer

I tried your way and it worked correctly.

List<AddressCandidate> returnedCandidates = args.Results;
AddressCandidate addCand = (
                from address in returnedCandidates
                orderby address.Score
                select address).Last();  


Thank you.
My pleasure