Home > Software engineering >  Determine which range a value falls under in c#
Determine which range a value falls under in c#

Time:10-30

I have an input type that contains a list of Min & Max values.I need to find out where a given value the given number falls under. The DTO looks similar to this

public class FeeDTO
{  
    public List<IndividualFee> Fees { get; set; }
}

public class IndividualFee
{   
    public int MinValue { get; set; }
    
    public int? MaxValue { get; set; }
    
    public string DiscountValue {get;set;}
}

So for example, this input would be fine as all ranges are exclusive:

Range 1: Min = 0 Max = 100 Discount = 20
Range 2: Min = 101 Max = 200 Discount = 30
Range 3: Min = 201 Max = 300 Discount = 40
Range 3: Min = 301 Max = null Discount = 50

Now if I have a number say 101 I want the discount 30 that I can retrieve and for a number say 302 I should be able to get 50.

I have tried ordering the set and then checking with the highest value first and then going by >= and I am able to get the result but just wondering if there a better efficient way rather than looping through all the values separately.

Thanks

CodePudding user response:

Using your example, I came up with a solution using List.Find:

IndividualFee fee1 = new IndividualFee() { MinValue = 0, MaxValue = 100, DiscountValue = @"20" };
IndividualFee fee2 = new IndividualFee() { MinValue = 101, MaxValue = 200, DiscountValue = @"30" };
IndividualFee fee3 = new IndividualFee() { MinValue = 201, MaxValue = 300, DiscountValue = @"40" };
IndividualFee fee4 = new IndividualFee() { MinValue = 301, MaxValue = null, DiscountValue = @"50" };
    
List<IndividualFee> list = new List<IndividualFee>();
list.Add(fee1);
list.Add(fee2);
list.Add(fee3);
list.Add(fee4);
    
int inputNumber = 101;
    
string discount = list.Find(f => inputNumber >= f.MinValue && inputNumber <= f.MaxValue).DiscountValue;
Console.WriteLine(discount);

CodePudding user response:

Using Enumerable.Range seems like a possible solution. try something like this:

int price = 30;
if (Enumerable.Range(min ,max).Contains(price)){
    // give discount
}

More about Enumerable.Range - https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.range?view=net-5.0

  • Related