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;
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();
I prefer using the order by clause....probably more efficient, too.
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.
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
(or, actually, LAST)
ASKER
re: jensfiederer,
I'm going to try to create an example using an order by clause and post it here.
I'm going to try to create an example using an order by clause and post it here.
ASKER
Our posts crossed.
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.
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