Search Feature using .Contains with terms within a one field

雨燕双飞 提交于 2019-12-23 20:42:24

问题


I have built a search feature for a product site. The search works fine. Recently, we have added a SearchTerm field in the database. SearchTerm Data example: "work shoes blue black gear" Current code is

    pM = (from p in ctx.Products
                      where
                            p.productSearchField.Contains(term) ||
                            p.productName.Contains(term)
                      select p).ToList()

If the term = "shoes" <-- works

If the term = "work shoes" <-- works

If the term = "black shoes" <-- does NOT work.

I also tried to separate the SearchTerm Data by commas, but that did not work. Any advice?


回答1:


Split the term into single terms. See if any match:

term.Split(' ').Any(i => p.productSearchField.Contains(i))

Or if every word has to match:

term.Split(' ').All(i => p.productSearchField.Contains(i))


EDIT
             var terms = term.Split(' ');
             pM = (from p in ctx.Products
                  where
                        terms.All(i => p.productSearchField.Contains(i)) ||
                        p.productName.Contains(term)
                  select p).ToList()


来源:https://stackoverflow.com/questions/8450887/search-feature-using-contains-with-terms-within-a-one-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!