60

Have a look at the below table:

Item          Value
A                10
b                50
c                90

I want to find the item with maximum value. I can get that by using group by or orderding, but somehow I have a feeling there should be a more direct way. Am I right?

1
  • Are you using Linq2Sql? Commented Mar 7, 2013 at 7:40

1 Answer 1

125

With EF or LINQ to SQL:

var item = db.Items.OrderByDescending(i => i.Value).FirstOrDefault();

With LINQ to Objects I suggest to use morelinq extension MaxBy (get morelinq from nuget):

var item = items.MaxBy(i => i.Value);
Sign up to request clarification or add additional context in comments.

15 Comments

@user1784622 I think this is pretty straight forward.
@user1784622 Max function of LINQ will return max value, not item with max value. I.e. for your items you will get 90
Yes, it's weird that Microsoft still haven't added MaxBy to the standard Enumerable extensions, given how many people want to use it. At least we have Jon Skeet's morelinq. :)
+1. If you can't for some reason use morelinq you can implement custom comparer and use corresponding version of .Net version of Max...
@user: You can reference your own libraries in Linqpad. There's an option to add references.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.