Haroon
Haroon

Reputation: 3472

Linq - getting a value that is between a lower limit and upper limit

I have a list of Fees (linq to sql entity- if relevant) - Upper Fee, Lower Fee (both are decimal values). I am passing in a property value - say 90000 and I want to check if this property value best matches one (or first value out of many) from the list of fees.

The fees could be something like...

(lower fee - upper fee)

0 - 50000
50001 - 75000
75001 - 90000
90001 - 140000
190000 - 500000

Out of these values, 90000 is best matched for something like 75001 - 90000 band, so I want to pull out that FeeDetail entity. I dont really know what operator to use, any help is appreciated, my code so far is...

    [Test]
    public void GetFeeRange()
   {
        const int id = 44;
        var propValue = 90000;

        //get a specific fee entity, then get the range of fee details...
        var recommendedFees = RepoSession.All<Fee>()
            .Where(x =>
                   x.ClientSurveyTypeID == id)
            .GroupJoin(_readOnlySession.All<FeeDetail>(),
                       x => x.FeeID,
                       y => y.FeeID,
                       (x, y) => new
                                     {
                                         FeeDetail = y.DefaultIfEmpty()
                                     })
            .Select(x => x.FeeDetail)
            .SingleOrDefault();

        Assert.IsNotNull(recommendedFees);

       //order fees by lowest fee - *the bit I am stuck on*
        var bestMatch = recommendedFees.OrderBy(x => x.Lower)
            .TakeWhile(x => propValue >= x.Lower || propValue <= x.Upper)
            .FirstOrDefault();



    }

Question- how would I perform the range checks? What operator of linq do I need? Not sure if I should perform a takewhile then, get the best fee from that range?

NOTE: the fees could very easily be...

(lower fee - upper fee)

0 - 50000
50001 - 75000
95001 - 140000
190000 - 500000

If a best match is found, pull that out OR get the closest match... maybe I can show a list of available matches if one is not (near enough) an exact match

Upvotes: 1

Views: 1839

Answers (3)

IAmGroot
IAmGroot

Reputation: 13855

var myfee = 90000;
var myFoundFeeRange = (from feeRange in feeRanges 
          where feeRange.lowerfee <= myfee && myfee <= feeRange.upperfee 
          select feeRange ).First()

This will do a simple check that the fee is within the boundary. And return the matching boundary

Upvotes: 1

hyp
hyp

Reputation: 1380

How about something like...

recommendedFees.Where(x => x.upperFee >= theFee).OrderByDescending(x => x.upperFee).Take(1).FirstOrDefault();

Upvotes: 1

Richard Dalton
Richard Dalton

Reputation: 35793

Just a simple .Where should be fine:

var bestMatch = recommendedFees
              .Where(x => propValue >= x.Lower && propValue <= x.Upper)
              .OrderBy(x => x.Lower)                  
              .FirstOrDefault();

Upvotes: 5

Related Questions