How to do a search from a list with non-prefix keywords

。_饼干妹妹 提交于 2019-12-06 01:27:47

Using LINQ you could write code like this:

var resultSet = products

    // filter products by category
    .Where(product => product.Category == "strings")

    // filter products by origin
    .Where(product => product.Origin == "italy")

    // filter products whose name contains a word starting with "guit"
    .Where(product => (" " + product.Name).Contains(" guit"))

    // limit the result set to the first 30 matching products
    .Take(30);

If your sets of products is reasonably small, you can use LINQ-to-Objects. Otherwise you should use a database and have a look at LINQ-to-SQL.

One word. Database!

Seriously, if you want to do all these different searches, consider placing your data into a database with a schema that simplifies the categorization issues you are having. Sql Server Express now supports full text search which would be very useful for the kind of search you are trying to perform.

There's a nice blog post here about using FTS with Linq-to-Sql.

static List<string> GetItemsWithWordsStartingWithSubstring(List<string> list, string substring)
{
    var query = from str in list
                from item in str.Split(' ')
                where item.StartsWith(substring, StringComparison.InvariantCultureIgnoreCase)
                select str;

    return query.ToList();
}

I hope I have read your intiial question properly. This function will return any item from the list that contains a word starting with your substring. More punctuation could be added to the split parameters. Given a list with the following contents:

"abcdef","defabc","def abc","xyz"

A search on "abc" will find "abcdef" and "def abc", but not "defabc".

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