Solved

# Find Max of Values using LINQ and Subquery

Posted on 2011-10-06
746 Views
I have a List of doubles, sorted ascending. How can I use LINQ to query the list for the maximum double in the list that is less than a random value I choose?
0
Question by:diablo089

LVL 21

Accepted Solution

double maxDouble = doubleList.Where( d => d > someRandomValue ).OrderByDescending().FirstOrDefault() );
0

LVL 96

Expert Comment

You forgot the Max operator...
0

Author Comment

Can you guys explain a little as to how this works? Thanks.
0

LVL 96

Expert Comment

What kind of explanation do you need?  Do you need to know how to compose a LINQ statement?  Do you need to know what the operator extension methods do?
0

LVL 21

Expert Comment

The statement I posted doesn't need a Max operator, it sorts the items descending and then grabs the first one (i.e. the max). But now that you mention it, this would also work.

double maxDouble = doubleList.Where( d => d > someRandomValue ).Max();
0

Author Comment

All of the above.
0

LVL 21

Assisted Solution

As to how it works.

doubleList is your list of doubles
Where( d => d > someRandomValue ) gives you a subset of that list where any element from the list (d) is greater than someRandomValue
Max() takes the maximum item from the list returned by the Where() method.
0

Author Comment

Thanks Craig. I appreciate your effort.
0

LVL 96

Expert Comment

The order of operations, says that you sort after the Where clause...
0

## Featured Post

### Suggested Solutions

Recently while returning home from work my wife (another .NET developer) was murmuring something. On further poking she said that she has been assigned a task where she has to serialize and deserialize objects and she is afraid of serialization. Wha…
In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
Hi everyone! This is Experts Exchange customer support.  This quick video will show you how to change your primary email address.  If you have any questions, then please Write a Comment below!
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.