Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

c# - LINQ query to match multiple words

I've been trying to solve this problem all day, and haven't found a solution that truly works. When I search for some data, I want to filter out the data based on multiple words.

My input value is split up by using the standard .Split-function.

string[] searchstrings = MessageResult.Split(' ');

I've made a query (which obviously doesn't work properly) that tries to filter out all the entries that matches every string in searchstrings.

                    var suggestions = (from a in query
                               from w in searchstrings
                               where a.Message.ToLower().Contains(w.ToLower())
                               select a).Distinct();

query is my variable which has all the data. How can I make this query to actually only match out entries that includes every string in searchstrings?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
var query = new string[]
{
    "abc foo bar xyz john doe",
    "abc foo bar xyz doe",
    "hello world",
    "abc foo bar john doe",
};

var searchstrings = new string[]
{
    "abc",
    "foo",
    "john",
    "xyz",
};

searchstrings = searchstrings.Select(x => x.ToLower()).ToArray();

var results = query.Select(x => x.ToLower())
                   .Where(x => searchstrings.All(y => x.Contains(y)));

Note:
ToLower() is performed outside the Where clause, to save a lot of calls to that method.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...