最近做MVC开发的项目,业务逻辑里边用到了很多条件累加查询的,现在我将方法贴出来供大家学习和参考。
public IQueryable<EspecHotelModel> GetAllEspecHotelInfo(string Position, DateTime? StartTime, DateTime? DepTime, string Rprice, string Commerical, string DistrictName, string Keyword)
{
HimsCNData db = new HimsCNData();
IQueryable<EspecHotelModel> list = from c in db.Htel_HotelCN
from e in db.Htel_HotelRoomEspecially
from h in db.Htel_Hotel
where c.HotelID == h.ID
where c.HotelID == e.Re_HotelId
where e.Re_State == 0
select new EspecHotelModel
{
HotelID = c.HotelID,
Description = c.Description,
Surrounding = c.Surrounding,
Address = c.Address,
NameCN = h.NameCN,
Discount = e.Re_Discount,
SalePrice = e.Re_Price,
list = GetAllEspecRoomInfo(c.HotelID),//房间信息
// SuperPrice=
// AreaID = h.AreaID,
FileName = "http://img.chinahotel.com/HotelImg/" + db.Htel_Photos.Where(o => o.HotelID == h.ID).First().FileName,//图片
Rating = GetStarString(h.Rating),
CommericalName= db.Com_AreaInfo.Where(o => o.ID == h.CommercialID).First().NameCN,
DistrictName = db.Com_AreaInfo.Where(o => o.ID == h.DistrictID ).First().NameCN,
};
if (list.Count() > 0)
{
//城市搜索
if (Position != "" && Position != null)
{
list = from l in list
join c in db.Com_AreaInfo
on l.AreaID equals c.ID into lc
from d in lc
where d.NameCN.Contains(Position)
select l;
}
//入住时间,离店时间
if (StartTime != null && DepTime != null)
{
list = from l in list
from h in db.Htel_HotelRoomEspecially
where l.HotelID == h.Re_HotelId
where h.Re_StartTime <= StartTime && h.Re_EndTime >= DepTime
select l;
}
//价格搜索
if (!string.IsNullOrEmpty(Rprice) && Rprice != "-1")
{
if (Rprice != "1500+")
{
int lprice = Convert.ToInt32(Rprice.Split('-')[0]);
int rprice = Convert.ToInt32(Rprice.Split('-')[1]);
list = from l in list
where l.SalePrice >= lprice && l.SalePrice <= rprice
select l;
}
else
{
list = from l in list
where l.SalePrice >= 1500
select l;
}
}
//商圈搜索
if (!string.IsNullOrEmpty(Commerical) && Commerical != "-1")
{
list = from l in list
where l.CommericalName.Contains(Commerical)
select l;
}
//行政区搜索
if (!string.IsNullOrEmpty(DistrictName) && DistrictName != "-1")
{
list = from l in list
where l.DistrictName.Contains(DistrictName)
select l;
}
//关键字搜索
if (!string.IsNullOrEmpty(Keyword) && Keyword != "-1")
{
list = from l in list
where l.NameCN.Contains(Keyword) || l.CommericalName.Contains(Keyword)//酒店名称和商业区
select l;
}
return list.Distinct().OrderByDescending(o => o.HotelID);
}
else
return null;
}