[英]C# How to match all items in an array to list of search terms
我有一個食譜 class:
public class Recipe
{
public string Id { get; set; }
public string RecipeTitle { get; set; }
public string ChefName { get; set; }
public List<string> HashTags { get; set; }
public string Ingredients { get; set; }
}
用戶可以在搜索框中輸入搜索詞列表,我想返回與所有搜索詞匹配的食譜。 到目前為止,這是我的代碼:
public Recipe[] SearchRecipes(string[] searchTerms, Recipe[] recipes)
{
var matches = new List<Recipe>();
foreach (var recipe in recipes)
{
if (searchTerms.Contains(recipe.ChefName, StringComparer.OrdinalIgnoreCase))
{
matches.Add(recipe);
}
foreach (var tag in recipe.Hashtags)
{
if (searchTerms.Contains(tag, StringComparer.OrdinalIgnoreCase))
{
matches.Add(recipe);
}
}
foreach (var title in recipe.RecipeTitle)
{
if (searchTerms.Contains(title, StringComparer.OrdinalIgnoreCase))
{
matches.Add(recipe);
}
}
}
return matches.Distinct().ToArray();
}
但是,這將返回僅匹配一個或兩個條件的項目。 例如,如果用戶搜索“Chef Jane”和“Difficult”,它也會返回來自“Chef Callum”的內容,因為存在“困難”標簽。
如何確保返回的唯一匹配項是完整匹配項?
我不確定遍歷該字符串中的成分的邏輯是什么,也許您也應該將它們列成一個列表。 無論如何,您可以為每個食譜創建一個食譜搜索詞數組,並返回所有用戶輸入搜索詞都被這些食譜搜索詞覆蓋的所有食譜。
public Recipe[] SearchRecipes(string[] searchTerms, Recipe[] recipes)
{
var matches = new List<Recipe>();
foreach (var recipe in recipes)
{
// Just flattening all the hash tags together with other recipe search terms
var recipeTerms = recipe.HashTags
.Concat(new string[]
{
recipe.RecipeTitle,
recipe.ChefName,
recipe.Ingredients
});
// Will include only the recipes where all search terms are matched in recipe terms
if (searchTerms.All(searchTerm =>
recipeTerms.Contains(searchTerm, StringComparer.OrdinalIgnoreCase))
{
matches.Add(recipe);
}
}
return matches.ToArray();
}
您也可以手動執行All
邏輯,但這種方式更簡單。 它來自System.Linq
命名空間,您可以在此處查看其文檔。
完整的 LINQ 解決方案如下所示:
public Recipe[] SearchRecipes(string[] searchTerms, Recipe[] recipes)
=> recipes.Where(recipe =>
{
var recipeTerms = recipe.HashTags
.Concat(new string[]
{
recipe.RecipeTitle,
recipe.ChefName,
recipe.Ingredients
});
return searchTerms.All(searchTerm =>
recipeTerms.Contains(searchTerm, StringComparer.OrdinalIgnoreCase));
})
.ToArray();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.