c# - 在 LINQ 查询中使用 "contains"时检查列表是否不为空,否则选择所有记录

标签 c# asp.net-mvc linq

我的应用程序中有一个搜索功能,它有 4 个标准,基本上是位置状态PropertyType [字符串列表]PriceRange [最低和最高价格] 下面是模型

public class SearchFilters
{
     public SearchFilters()
     {
          MinPrice = "10000";
          MaxPrice = "8000000";
     }
     public IEnumerable<SelectListItem> Categories { get; set; }
     public string[] CategoriesId { get; set; }

     public IEnumerable<SelectListItem> Locations { get; set; }
     public string[] LocationID { get; set; }

     public IEnumerable<SelectListItem> Status { get; set; }
     public string[] StatusID { get; set; }

     public string MinPrice { get; set; }
     public string MaxPrice { get; set; }
}

controller 中接收到数据时,从 SelectList 中选择的值列表将存储在 CategoriesIdLocationID 中和 StatusID。现在从每个列表中选择值是可选的,它可以是单个或多个。所以我需要过滤数据库,如果用户没有选择任何项目,那么这个 List 将是 null 因为它是一个可选的搜索条件。

例如

状态值可以是“进行中”、“即将到来”和“已完成”。所以我在下面使用 LINQ 来提取数据。

[HttpGet]
public ActionResult Search(SearchFilters smodel)
{
     var query=db.tblProperties.Where(p => smodel.StatusID.Contains(p.PropertyLocation)).Select(x=>x).ToList();
     //.....
     //.....

}

Just added one property comparison to demonstrate

这会毫无问题地返回记录,但是如果此 smodel.StatusID 出现 null 即用户未选择任何值,则此查询失败并出现 exception。那么如何克服呢?还有如何在没有选择值的情况下获取所有的记录?经历了 this post 但是那里的解决方案对克服这个问题没有用?基本上,在这些情况下我如何合并搜索查询?

最佳答案

发布的答案是正确的,并为您提供了所需的解决方案,如果您在几个地方需要这种行为,我将继续检查 null。如果此请求在很多地方重复出现,我将采用以下解决方案。

如果您要进行大量此类检查,还有另一种更简洁的方法,即添加 Extension Methods为你做。

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

代码:

public static class CollectionExtension
{
    public static bool CheckContainsIfHasValue<T>(this IEnumerable<T> source, T value)
    {
        return source == null || source.Contains(value);
    }
}

用法:

var query = db.tblProperties
            .Where(p => smodel.StatusID.CheckContainsIfHasValue(p.PropertyLocation))
            .ToList();

关于c# - 在 LINQ 查询中使用 "contains"时检查列表是否不为空,否则选择所有记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34816922/

相关文章:

c# - CSV 读数为空

c# - 我什么时候必须编译asp.net 4.0 项目?

C# 使用 Template10 在汉堡菜单中显示用户名

c# - 为 SpecBind 设置 Selenium Web 驱动程序

c# - ASP.NET MVC 授权具有多个角色的用户

javascript - 通过 AJAX 将 JSON 对象发布到 ASP.NET Core Web API

c# - 如何使用 LINQ、C# 向元素添加属性?

c# - 模拟 ViewContext 以测试验证错误消息

c# - 如何重置 C# 中的标识列?

python - python 中类似 linq 的求和函数