C# LINQ-必填字段,不关心是否为空
我正在asp.net应用程序中构建搜索功能,并使用LINQ to SQL根据所选搜索条件检索数据。搜索条件如下:C# LINQ-必填字段,不关心是否为空,c#,.net,linq,C#,.net,Linq,我正在asp.net应用程序中构建搜索功能,并使用LINQ to SQL根据所选搜索条件检索数据。搜索条件如下: 国家 城市 地区 房间数 租金周期 只有第一个搜索条件Country是必填字段。但是,如果用户输入了条件2、3、4和/或5的值,则应考虑输入的值,并仅检索与所有输入的搜索条件匹配的结果。请注意,如果条件2、3、4和/或5中的一个为空(null),则LINQ应充当“不关心”并返回该行 例如,如果输入的标准是: 国家=美国 城市=空 地区=空 房间数=空 租金周期=空 然后应返回Coun
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;
我的基本意思是,如果要搜索的变量为空,则忽略它们,否则将它们与
单元中的相应字段相匹配,您可以分阶段建立查询:
var query = from x in db.Units where x.Country == countryId;
if (cityId != null) query = query.Where(x.City == cityId);
if (districtId != null) query = query.Where(x.City == districtId);
if (rooms != null) query = query.Where(x.Rooms == rooms);
if (rentCycle != null) query = query.Where(x.RentCycle == rentCycle);
var data = query.Select();
如果使用GetValuerDefault稍微弄乱了C#,那么SQL的效率会稍微提高一些,如果为null,则为当前值提供默认值:
var data = from x in db.Units
where x.Country == countryId
&& (x.City == cityId.GetValueOrDefault(x.City))
&& (x.District == districtId.GetValueOrDefault(x.District))
&& (x.Rooms == rooms.GetValueOrDefault(x.Rooms))
&& (x.RentCycle == rentCycle.GetValueOrDefault(x.RentCycle))
select x;
如果我必须为相同的功能从多个表中获取记录,那么我如何才能实现它。Thanks@User只需使用外部接头,请举例说明。