gpt4 book ai didi

.net - 无需使用多个 IFS 即可搜索我的网站

转载 作者:搜寻专家 更新时间:2023-10-30 19:42:13 24 4
gpt4 key购买 nike

我想在我的数据库中搜索表中的产品(产品)问题是我不想要 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com