John Ohara
John Ohara

Reputation: 2901

Use linq to select a range that overlaps another range

I have a list that contains a number of 'bands', as follows:

var bands = new List<Band>();

bands.Add(new Band(1, 12, 1, 100, 199, 100, 292));
bands.Add(new Band(1, 5, 1, 200, 1000, 100, 292));
bands.Add(new Band(6, 6, 1, 200, 2000, 100, 210));
bands.Add(new Band(7, 7, 1, 200, 2000, 100, 192));
bands.Add(new Band(8, 8, 1, 200, 2000, 100, 178));
bands.Add(new Band(9, 9, 1, 200, 2000, 100, 167));
bands.Add(new Band(10, 10, 1, 200, 2000, 100, 158));
bands.Add(new Band(11, 11, 1, 200, 2000, 100, 150.5));
bands.Add(new Band(12, 12, 1, 200, 999, 100, 140));
bands.Add(new Band(12, 18, 3, 1000, 3000, 100, 71.3));
bands.Add(new Band(24, 24, 6, 1000, 3000, 100, 71.3));

The important columns are 4 and 5 - the first band values being 100 and 199.

Presently, I have a query that selects one or more bands based on a single parameter:

public static IEnumerable<Quote> ForAmount(int amount)
{
    return Repository.Bands
        .Where(x => amount >= x.MinAmount && amount <= x.MaxAmount)
        .YieldTerms(amount); // this does something with the selected data
}

However, I'd like to pull out bands that fall within a low and high range.

New signature:

public static IEnumerable<Quote> ForAmount(int lowAmount, int highAmount)
{
    // Query
}

So, for instance Low = 100 and High = 500.

Given the example high/low values, the following band would be selected (100 - 500 overlaps 100 - 199).

bands.Add(new Band(1, 12, 1, 100, 199, 100, 292));

So would the following band (100 - 500 overlaps 200 - 2000).

bands.Add(new Band(1, 5, 1, 200, 1000, 100, 292));

I'm sure this is easily done, but I've got brain fog right now, so any help appreciated.

Upvotes: 1

Views: 400

Answers (2)

Ayberk
Ayberk

Reputation: 560

I have demonstrated something similar to your example in dotnet fiddle; https://dotnetfiddle.net/dHr2Nn

This should be working.

public static IEnumerable<Quote> ForAmount(int lowAmount, int highAmount)
{
    return Repository.Bands
        .Where(x => x.MinAmount <= highAmount && x.MinAmount >= lowAmount) 
             || (x.MaxAmount >= lowAmount && x.MaxAmount <= highAmount))
        .YieldTerms(...); // this does something with the selected data
}

Upvotes: 0

Klaus G&#252;tter
Klaus G&#252;tter

Reputation: 11997

Repository.Bands
    .Where(x => x.MinAmount <= High && x.MaxAmount >= Low)

should do it

Upvotes: 2

Related Questions