如果where包含空字符串,LINQ应该不返回任何记录

时间:2016-03-11 15:01:15

标签: asp.net-mvc linq linq-to-sql

我正在尝试获取汽车描述过滤器文本的汽车记录。但是如果过滤器文本为空,我不应该返回任何记录。以下代码正在运行,但有更好的方法可以避免使用cars.where(c => false)

public JsonResult GetCars(string cFilter)
{
    IQueryable<Cars> cars = CarService.GetCars();
    if (!string.IsNullOrEmpty(cFilter))
        cars = cars.Where(c => c.carDescr.Contains(cFilter));
    else
        cars = cars.Where(c => false);
    var carInfo = (from c in cars
                      select (new { id = c.CarID, description = c.CarID + "-" + c.carDescr })).ToList();
    return Json(carInfo, JsonRequestBehavior.AllowGet);
}

3 个答案:

答案 0 :(得分:2)

您可以完全跳过CarService的使用。

public JsonResult GetCars(string cFilter)
{
  IQueryable<Cars> cars;
  if (!string.IsNullOrEmpty(cFilter))
    cars = CarService.GetCars().Where(c => c.carDescr.Contains(cFilter));
  else
    cars = Enumerable.Empty<Cars>().AsQueryable();

  var carInfo = (from c in cars
                 select (new { id = c.CarID, description = c.CarID + "-" + c.carDescr })).ToList();
  return Json(carInfo, JsonRequestBehavior.AllowGet);
}

你可以缓存由EnumerableQuery<Cars>生成的Enumreable.Empty<Cars>(),或者在任何情况下只返回JsonResult一个空数组,因为任何空的json数组都是空的json数组:

public JsonResult GetCars(string cFilter)
{
  if (!string.IsNullOrEmpty(cFilter))
    return Json(Enumerable.Empty<object>(), JsonRequestBehavior.AllowGet);

    var carInfo = (from c in CarService.GetCars()
                      where c.carDescr.Contains(cFilter)
                      select (new { id = c.CarID, description = c.CarID + "-" + c.carDescr })).ToList();
    return Json(carInfo, JsonRequestBehavior.AllowGet);
}

我会选择后者,但值得一提的是前者适用于两者中唯一适用的情况。

答案 1 :(得分:0)

我不知道我错过了什么,但你只为cFilter设置了null public JsonResult GetCars(string cFilter) { IQueryable<Cars> cars = CarService.GetCars(); if (!string.IsNullOrEmpty(cFilter)) {cars = cars.Where(c => c.carDescr.Contains(cFilter)); var carInfo = (from c in cars select (new { id = c.CarID, description = c.CarID + "-" + c.carDescr })).ToList(); return Json(carInfo, JsonRequestBehavior.AllowGet); } else { return Json("", JsonRequestBehavior.AllowGet); } }

var matcher='Hello';
var s1='hello everyone';
s=s1.split(" ");
(s[0].toUpperCase() ===matcher.toUpperCase() )?console.log(s[1]):console.log("nothing");

答案 2 :(得分:0)

得到另一种解决方案。在where子句中添加了cFilter empty或null检查,并且它有效。

cars = cars.Where(c => c.carDescr.Contains(cFilter) && !string.IsNullOrEmpty(cFilter));

以下完整功能。

public JsonResult GetCars(string cFilter)
        {
            IQueryable<Cars> cars = CarService.GetCars();
            cars = cars.Where(c => c.carDescr.Contains(cFilter) && !string.IsNullOrEmpty(cFilter));
            var carInfo = (from c in cars
                           select (new { id = c.CarID, description = c.CarID + "-" + c.carDescr })).ToList();
            return Json(carInfo, JsonRequestBehavior.AllowGet);
        }