If the input value is between MinIncome and MaxIncome in my database table, I want to find the Amount db field value. So for instance if an input was 1525 falling between 1500 & 1599, I would expect a return value of 75.
How do I write a Linq or Lambda statement for this? Please see screen shot.
CodePudding user response:
int income = 1525;
int amount = dbContext
.MyDbSet // use DbSet Property here
.Single(x => x.MinIncome < income && x.MaxIncome > income)
.Amount;
This selects the only element where the condition is met, and returns the amount of that object.
You could also use .Where(x => x.MinIncome < income && x.MaxIncome > income).Single().Amount
to achieve the exact same result.
Other options include .SingleOrDefault()
which prevents errors in case no entry in your DbSet
matches, .First()
which prevents errors if multiple entries match, or .FirstOrDefault()
if no entries or multiple entries can match.
CodePudding user response:
Try this:
var result = await DbContext
.Table
.Where(x => x.MinIncome <= value && value <= x.MaxIncome)
.Select(x => x.Amount).FirstOrDefaultAsync();