我在创建linq时遇到一些困难,我需要复制下面的SQL语句。
SELECT TOP (1000) [Id]
,[Price]
,[ThicknessFrom]
,[ThicknessTo]
,[WeightFrom]
,[WeightTo]
FROM [dbo].[MyTable]
WHERE (8 between [ThicknessFrom] and [ThicknessTo])
AND (100 between [WeightFrom] and [WeightTo])
我拥有的数据示例:
id: 1, price: 1, thicknessFrom: 0, thicknessTo: 10, weightFrom: 0, weightTo: 125
id: 2, price: 2, thicknessFrom: 11, thicknessTo: 20, weightFrom: 126, weightTo: 250
我想从上面的linq语句返回查询,该语句将返回基于2个输入,重量和厚度的数据,这将返回id = 1。
感谢
答案 0 :(得分:4)
MyTable.Where(entities => entities.ThicknessFrom <= 8)
.Where(entities => entities.ThicknessTo >= 8)
.Where(entities => entities.WeightFrom <= 100)
.Where(entities => entities.WeightTo >= 100)
.Take(1000);
我们上面所做的是链接多个谓词以保持清洁/易于阅读,在执行.Take()
方法之前,查询实际上并未执行。
答案 1 :(得分:1)
让inputThicknes
和inputWeight
成为两个输入,然后您可以像下面这样创建LINQ,它将为您提供所需的结果:
var requiredCollection = (from t in db.MyTable where
t.ThicknessFrom < inputThicknes &&
t.ThicknessTo >= inputThicknes &&
t.WeightFrom < inputWeight &&
t.WeightTo >= inputWeight
select t).Take(1000)