Nate Pet
Nate Pet

Reputation: 46222

Linq Get Max from List of Records

I have the following table

ID Amt  Received  SchoolAmt
-- ---- --------  -------
2  55   N          
2  88   Y          7
2  44   N          6  
3  5    N
3  9    N
4  5    N          32
5  33   Y
6  43   N
7  54   N          66

For a given ID, I need to find the Max Amount and then check to see if it is Marked as Y, if so, mark the result as boolean true of false.

One way to do this would be:

    db.Exp.
    Where(x => x.ID == id)
    .OrderByDescending(x => x.Amt)
    .Take(1)
    .Any(x => x.Received == "Y"); 

which works but I also need to add that SchoolAmt should also be greater than 0.

Why is the following not working:

    db.Exp.
    Where(x => x.ID == id)
    .OrderByDescending(x => x.Amt)
    .Take(1)
    .Any(x => x.Received == "Y" && x => x.SchoolAmt > 0);

When I try to type in x => x.SchoolAmt > 0 Visual studio does not allow it as it seems to be the incorrect syntex.

Upvotes: 2

Views: 146

Answers (3)

Gent
Gent

Reputation: 2685

I would suggest adding the MoreLinq library via Nuget this will give you the MaxBy/MinBy extensions, then using the following

 db.Exp.
    Where(x => x.ID == id)
    .MaxBy(x => x.Amt)
    .Any(x => x.Received == "Y" && x.SchoolAmt > 0);

Upvotes: 0

devdigital
devdigital

Reputation: 34349

Try

.Any(x => x.Received == "Y" && x.SchoolAmt > 0);

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564413

The predicate should be written as:

.Any(x => x.Received == "Y" && x.SchoolAmt > 0);

This is a single delegate, which gets mapped to a function that looks something similar to:

static bool someCompilerGeneratedName(YourClass x)
{
    return x.Received == "Y" && x.SchoolAmt > 0; 
}

Since this is a single delegate, and a single method, you only need the => in there at the beginning to create the lambda. The two criteria checks use the same variable (x).

Upvotes: 0

Related Questions