我正在 asp.net 应用程序中构建搜索功能,我正在使用 LINQ to SQL 根据选定的搜索条件检索数据。搜索条件是
- 国家
- 城市
- 区
- 房间数
- 租金周期
只有第一个搜索条件“国家/地区”是必填字段。但是,如果用户输入了条件 2、3、4 和/或 5 的值,则应考虑输入的值,并且仅检索与所有输入的搜索条件相匹配的结果。请注意,如果条件 2、3、4 和/或 5 之一留空 (null),则 LINQ 应充当“DONT CARE”并返回该行。
例如,如果输入的条件是:
- 国家=美国
- 城市 = null
- 地区 = null
- 房间数 = null
- 租金周期 = null
然后应返回所有带有 Country == USA 的行。
另一个例子:
- 国家=英国
- 城市 = null
- 地区 = null
- 房间数 = 5
- 租金周期 = null
然后应返回所有包含 Country == UK 和 NumberOfRooms == 5 的行。
如何在 LINQ to SQL 中实现这一点?
这是我目前所拥有的:
var data = from x in db.Units where x.Country == coutnryID && /*PLEASE HELP!*/ select x;
最佳答案
试试这个(假设 cityId
、districtId
、rooms
和 rentCycle
是您想要的变量搜索:
var data = from x in db.Units
where x.Country == countryId
&& (cityId == null || x.City == cityId)
&& (districtId == null || x.District == districtId)
&& (rooms == null || x.Rooms == rooms)
&& (rentCycle == null || x.RentCycle == rentCycle)
select x;
我基本上是说,如果您要搜索的变量为空,则忽略它们,否则将它们与 Unit
中的相应字段匹配。
关于c# - LINQ - 必填字段,不关心是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10741623/