我有一個Card帶有屬性的物體Title。我還有一個欄位可以使用搜索詞搜索所有卡片的標題。假設我有卡片標題“黑魔法師”和“藍眼龍”。如果我搜索“魔術師龍”,我需要收到兩張卡,如果我搜索“有房子的藍狗”,我需要收到“藍眼龍”卡。到目前為止,我有這段代碼,但我無法撰寫正確的 LINQ 代碼。
CardsController.cs,所有視圖:
public IActionResult All(string searchTerm)
{
var cardsQuery = this.data.Cards.AsQueryable();
if (!string.IsNullOrWhiteSpace(searchTerm))
{
//Removing all the white spaces and then joining the different words by a space
searchTerm = string.Join(" ", searchTerm.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries));
//Splitting the searchTerm and making it a list of strings
var searchTermSplitted = searchTerm.Split().ToList();
//Trying to check if any and which words are contained in any of the cards' titles
cardsQuery = cardsQuery
.Where(c => c.Title.ToLower().Contains(searchTermSplitted)); //Not working, just for the idea
}
var cards = cardsQuery
.OrderByDescending(c => c.Id)
.Select(c => new CardListingViewModel
{
Title = c.Title,
ImageUrl = c.ImageUrl,
Category = c.Category.Name,
Condition = c.Condition.Name
})
.ToList();
return View(new AllCardsQueryModel
{
Cards = cards
}); ;
}
uj5u.com熱心網友回復:
嘗試以下:
List<Card> cards = new List<Card>();
string searchPattern = "Magician Dragon";
List<string> searchWords = searchPattern.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();
var results = cards.AsEnumerable().Where(x => searchWords.Any(y => x.Title.Contains(y))).ToList();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/510711.html
標籤:C#林克
