作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我想在我的数据库中搜索表中的产品(产品)问题是我不想要 600 行带有多个 if 的代码。代码如下 atm(不要这样)
Public Function GetSearchResults(ByVal County As Integer, Optional ByVal Searchtext As String = "", Optional ByVal Category As Integer = 0, Optional ByVal SubCategory As Integer = 0) As List(Of Product)
Dim dc As New DataClassesDataContext
Dim Listholder As New List(Of Product)
If Searchtext IsNot "" Then
If County > 0 Then
If Category > 0 Then
If SubCategory = 0 Then
Dim Results = From p In dc.Products _
Where p.Headline.Contains(Searchtext) _
Where p.CategoryID = Category _
Where p.CountyID = County _
Select p
Listholder = Results.ToList
Return Listholder.ToList
还有很多 elseifs 等等...问题是,如果上述任何一项的值为 0,则搜索将针对所有县/类别/标题....是否有更好的方法来执行此操作?我的意思是 linq 很棒,必须有办法让它更动态,所以我不需要 IFS。
最佳答案
您可以链接您的 Where 过滤器。
public static void Search(String headline = null, Int32 county = 0, Int32 category = 0, Int32 subCategory = 0) {
var dc = new DataClassesDataContext();
var result = dc.Products;
if (headline != null)
result = result.Where(p => p.Headline.Contains(headline));
if (county != 0)
result = result.Where(p => p.CountyId == county);
if (category != 0)
result = result.Where(p => p.CategoryId == category);
if (subCategory != 0)
result = result.Where(p => p.SubCategoryId == subCategory);
var listHolder = result.ToList();
// ...
}
关于.net - 无需使用多个 IFS 即可搜索我的网站,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4596065/
我是一名优秀的程序员,十分优秀!