Link to home
Start Free TrialLog in
Avatar of pzozulka
pzozulka

asked on

LINQ: How to get a min value from a DataTable

I have a DataTable which returned two columns, both decimals.

Column 1: Upper Bound Amount
Column 2: Fee Amount

I want to use the LINQ MIN function to get the minimum Fee Amount where Upper Bound Amount < $25.00 (for example).

So far, I have the following:
DataTable dt = Mapper.GetAllFees();
decimal feeAmount = dt.AsEnumerable()
	.Where(ub => ub.Field<decimal>("UpperBoundAmount") > 25.00)
	.Select(fa => fa.Field<decimal>("FeeAmount"))
	.FirstOrDefault();

Open in new window

How do I incorporate the MIN function into that LINQ statement to say something like:

.Min(ub => ub.Field<decimal>("UpperBoundAmount"))
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Hi pzozulka;

If I understand your question, not clear from the post, the following should do what you want.
DataTable dt = Mapper.GetAllFees();
decimal feeAmount = dt.AsEnumerable()
                      .Where(ub => ub.Field<decimal>("UpperBoundAmount") < 25.00)
	              .Select(fa => fa.Field<decimal>("FeeAmount"))
	              .Min(fa => fa);

Open in new window

Avatar of pzozulka
pzozulka

ASKER

Sorry I wasn't clear.

Here's what I need, based on the following sample:

UpperBoundAmount        FeeAmount
100.00                                  19.00
90.00                                     17.00
50.00                                     16.00
22.00                                      9.00
20.00                                      8.00
11.00                                      7.00
11.00                                      7.00

I need to select all rows where "UpperBoundAmount" < 25.00. The results are below:

UpperBoundAmount        FeeAmount
22.00                                      9.00
20.00                                      8.00
11.00                                      7.00
11.00                                      7.00

Based on the remaining list, I need to select the row, with the MIN(UpperBoundAmount). Results are:
UpperBoundAmount        FeeAmount
11.00                                      7.00
11.00                                      6.00

Next, from those results, I need to select the FirstOrDefault() FeeAmount.
ASKER CERTIFIED SOLUTION
Avatar of Fernando Soto
Fernando Soto
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
SOLUTION
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
Hi  pzozulka;

Are you still having issues with this question, or has it been resolved?