nologo
nologo

Reputation: 6278

Linq value between 2 column ranges

i'm having a little difficulty creating the linq i need to replicate the below SQL statement.

    SELECT TOP (1000) [Id]
      ,[Price]
      ,[ThicknessFrom]
      ,[ThicknessTo]
      ,[WeightFrom]
      ,[WeightTo]
  FROM [dbo].[MyTable] 
  WHERE (8 between [ThicknessFrom] and [ThicknessTo])
  AND (100 between [WeightFrom] and [WeightTo])

Example of the data i have:

id: 1, price: 1, thicknessFrom: 0, thicknessTo: 10, weightFrom: 0, weightTo: 125
id: 2, price: 2, thicknessFrom: 11, thicknessTo: 20, weightFrom: 126, weightTo: 250

i want to return the query from an above linq statement that would return data based on 2 inputs, weight and thickness which would return id = 1.

thanks

Upvotes: 1

Views: 880

Answers (2)

Aydin
Aydin

Reputation: 15294

MyTable.Where(entities => entities.ThicknessFrom <= 8)
       .Where(entities => entities.ThicknessTo >= 8)
       .Where(entities => entities.WeightFrom <= 100)
       .Where(entities => entities.WeightTo >= 100)
       .Take(1000);

What we're doing above is chaining multiple predicates to keep things clean / easy to read, the query isn't actually executed until the .Take() method is executed.

Upvotes: 6

sujith karivelil
sujith karivelil

Reputation: 29006

Let inputThicknes and inputWeight be the two inputs, then you can create the LINQ like the following, which will give you the required result:

var requiredCollection = (from t in db.MyTable where 
                               t.ThicknessFrom < inputThicknes  && 
                               t.ThicknessTo >= inputThicknes  &&
                               t.WeightFrom < inputWeight &&
                               t.WeightTo >= inputWeight
                          select t).Take(1000)

Upvotes: 1

Related Questions